node.js get request from zero

At present front-end development path is more broad, from simple page cubs to ajax interaction now and then to keep pace troika, JavaScript bursting out its proper glory, now the front-end programmers will also Node.js master a skill, then what is Node.js it? Roughly speaking that is running the service side JavaScript (here chiefs ignored such talk is inaccurate), then let us start learning it now!

  In front of those who repeat them not long-winded, such as what is Node, http protocol which there will no longer be written, are interested can look at the relevant introduction, today we have direct access to the theme of today, how native Node is processed get request.

// First introduced Node http module carrying 
const = http the require ( 'http' ); 
const QueryString = the require ( 'querysting');

The next step is to create an interface service:

// create objects need to monitor processing information received and return the information to the front 
const Server = http.createServer ((REQ, RES) => {
    // we can print it and see what is the way our request 
   console.log ( req.method)
// receive routing 
const url = req.url; 
// print here look at this url is what 
console.log ( 'url:' , url); 

? // Here we intercept url parameter back and we can print it out to see look 
req.query = querystring.parse (url.split () [1 '?' ]) 
console.log ( 'Query:', req.query) 

// at the end we will convert him into a string
res.end (
  JSON.stringify (req.query)
)
})
// the ok this point our entire receiving process is processed

 Finally, we need to listen to this service

server.listen (9000); // we have to listen to this service port 9000 

// In order to be able to clearly see the whole process is complete, we print a the ok 
console.log ( 'the OK')

Here we get to do the front end processing the request sent is complete, then we start to try this file

ok here shows that our server has been running, we initiated the request to the front-end interface to try

In the browser we can see the information we request is sent, the user is Joe Smith, keyword is A

In our server we can clearly see that we are using, as the GET request, url is

/api/blog/list?author=zhangsan&keyword=A

And what is the content of our query

What about our Node.js get request it, there are so many here, we will be back often to use

 

Complete code is as follows:

const http = require('http');
const querystring = require('querystring');const server = http.createServer((req,res)=>{
    console.log(req.method);
    const url = req.url;
    console.log('url:',url);
    req.query = querystring.parse(url.split('?')[1]);
    console.log('query',req.query);
    res.end(
        JSON.stringify(req.query)
    )
});

server.listen(9000);
console.log('OK');

 

Guess you like

Origin www.cnblogs.com/yang656/p/11071816.html