Parsing Query String in node.js

后端 未结 5 1201
生来不讨喜
生来不讨喜 2020-12-22 23:11

In this \"Hello World\" example:

// Load the http module to create an http server.
var http = require(\'http\');

// Configure our HTTP server to respond wit         


        
5条回答
  •  醉酒成梦
    2020-12-22 23:55

    node -v v9.10.1

    If you try to console log query object directly you will get error TypeError: Cannot convert object to primitive value

    So I would suggest use JSON.stringify

    const http = require('http');
    const url = require('url');
    
    const server = http.createServer((req, res) => {
        const parsedUrl = url.parse(req.url, true);
    
        const path = parsedUrl.pathname, query = parsedUrl.query;
        const method = req.method;
    
        res.end("hello world\n");
    
        console.log(`Request received on: ${path} + method: ${method} + query: 
        ${JSON.stringify(query)}`);
        console.log('query: ', query);
      });
    
    
      server.listen(3000, () => console.log("Server running at port 3000"));
    

    So doing curl http://localhost:3000/foo\?fizz\=buzz will return Request received on: /foo + method: GET + query: {"fizz":"buzz"}

提交回复
热议问题