Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

node js http request

// Importing https module
const http = require('http');
  
// Setting the configuration for
// the request
const options = {
    hostname: 'jsonplaceholder.typicode.com',
    path: '/posts',
    method: 'GET'
};
    
// Sending the request
const req = http.request(options, (res) => {
    let data = ''
     
    res.on('data', (chunk) => {
        data += chunk;
    });
    
    // Ending the response 
    res.on('end', () => {
        console.log('Body:', JSON.parse(data))
    });
       
}).on("error", (err) => {
    console.log("Error: ", err)
}).end()
Comment

http node

var fs  = require("fs")
var http  = require("http")

//in this example, I try to show an image
http.createServer((req, res) => {

    fs.readFile(`./images/${req.url}.jpg`, (err, data) => {
        if(err) {
            res.writeHead(404, {'Content-Type': 'text/plain'})
            res.end('Img not found')
        } else {
            res.writeHead(200, {'Content-Type': 'image/jpg'})
            res.end(data)
        }
    })
//change 3000 if you prefer
}).listen(1337, 'localhost')
Comment

http request node.js

var http = require('http');

//The url we want is: 'www.random.org/integers/?num=1&min=1&max=10&col=1&base=10&format=plain&rnd=new'
var options = {
  host: 'www.random.org',
  path: '/integers/?num=1&min=1&max=10&col=1&base=10&format=plain&rnd=new'
};

callback = function(response) {
  var str = '';

  //another chunk of data has been received, so append it to `str`
  response.on('data', function (chunk) {
    str += chunk;
  });

  //the whole response has been received, so we just print it out here
  response.on('end', function () {
    console.log(str);
  });
}

http.request(options, callback).end();
Comment

nodejs http

const http = require('http')

const server = http.createServer((req, res) => {
  if (req.url === '/') { //Home Page
    res.end('Welcome to our home page')
  } else if (req.url === '/about') { //About page
    res.end('Here is our short history')
  } else {
    res.end(`
    <h1>Oops!</h1>
    <p>We can't seem to find the page you are looking for</p>
    <a href="/">back home</a>
    `) // Page not found
  }
})

server.listen(5000)
console.log('Server is listening on port 5000')
Comment

node http request

const http = require('http');

http.createServer((request, response) => {
  const { headers, method, url } = request;
  let body = [];
  request.on('error', (err) => {
    console.error(err);
  }).on('data', (chunk) => {
    body.push(chunk);
  }).on('end', () => {
    body = Buffer.concat(body).toString();
    // BEGINNING OF NEW STUFF

    response.on('error', (err) => {
      console.error(err);
    });

    response.statusCode = 200;
    response.setHeader('Content-Type', 'application/json');
    // Note: the 2 lines above could be replaced with this next one:
    // response.writeHead(200, {'Content-Type': 'application/json'})

    const responseBody = { headers, method, url, body };

    response.write(JSON.stringify(responseBody));
    response.end();
    // Note: the 2 lines above could be replaced with this next one:
    // response.end(JSON.stringify(responseBody))

    // END OF NEW STUFF
  });
}).listen(8080);
Comment

PREVIOUS NEXT
Code Example
Javascript :: counting sheep 
Javascript :: jquery validate all input fields 
Javascript :: findone and update mongoose 
Javascript :: date and time javascript 
Javascript :: return inside ternary operator javascript 
Javascript :: how to make an event listener only work once 
Javascript :: js string to int 
Javascript :: js redux example 
Javascript :: updating json object in mysql database 
Javascript :: clone aJavaScript object 
Javascript :: template literal syntax 
Javascript :: js check string is date 
Javascript :: date compare in js 
Javascript :: js slice string at word 
Javascript :: for...of Syntax 
Javascript :: find how many similar object item in an array in javascript 
Javascript :: mdn object assign 
Javascript :: js detect object has key 
Javascript :: my angular modal popup is not closing automatically 
Javascript :: how to get MathJax 
Javascript :: js for loop plus number 
Javascript :: node settimeout 
Javascript :: Children in JSX 
Javascript :: const name value = event.target 
Javascript :: javascript find factorial 
Javascript :: What is array.push in javascript 
Javascript :: javascript /g 
Javascript :: array sort numbers 
Javascript :: flat function javascript 
Javascript :: javascript string spaces replace with %20 
ADD CONTENT
Topic
Content
Source link
Name
2+4 =