req.query在nodejs中的Http.createserver中不起作用?

时间:2018-11-09 16:06:12

标签: node.js http httpserver

大家好我是NodeJS的初学者,无论如何获取get请求中的数据,都无法获得该值。它显示错误“无法读取未定义的属性'user'”。我在浏览器中输入的网址是 http://localhost:8086/dopath?user=viki&pass=vino 我附加了代码。任何人都可以解决此问题吗?谢谢……

"use strict";
let http=require('http');
let url=require("url");
let port=process.env.PORT||8086;
function handler(req,res)
{
    if(req.url!="/favicon.ico")
    {
        let urldata=url.parse(req.url);
        console.log(urldata);
        console.log("Request Method:"+req.method);
        console.log("Request URL:"+req.url);
        console.log("Username:"+req.query.user);
        console.log("Password:"+req.query.pass);
        res.statusCode=200;
        res.setHeader('content-Type','text/plain');
        res.end("I 'm sending data username is "+`${req.query.user}`+"and password is "+`${req.query.pass}`);
    }
}
let server=http.createServer(handler);
server.listen(port,()=>{
    console.log("server is listening on port",`${port}`);
});

1 个答案:

答案 0 :(得分:2)

请在代码中使用空格,否则难以阅读。当变量不变时,也使用const代替let。您忘了使用解析后的urlData。

尝试一下:

'use strict'

const http = require('http')
const url = require('url')
const port = process.env.PORT || 8086

function handler (req, res) {  
  if (req.url !== '/favicon.ico') {
    const urlData = url.parse(req.url, true)

    console.log(req.query)
    console.log(urlData)
    console.log('Request Method:' + req.method)
    console.log('Request URL:' + req.url)
    console.log('Username:' + urlData.query.user)
    console.log('Password:' + urlData.query.pass)
    res.statusCode = 200
    res.setHeader('content-Type', 'text/plain')
    res.end("I 'm sending data username is " + `${urlData.query.user}` + 'and password is ' + `${urlData.query.pass}`)
  }
}

const server = http.createServer(handler)

server.listen(port, () => {
  console.log('server is listening on port', `${port}`)
})