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

req.query is not working in Http.createserver in nodejs?

大家好,我是 NodeJS 的初学者,无论给定的数据如何,我都无法获得值 request.It 显示错误 "Cannot read property 'user' of undefined"。这是我在浏览器中给出的 url http://localhost:8086/dopath?user=viki&pass=vino 我附上 code.can 有人解决了这个问题吗?在此先感谢...

"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}`);
});

请在代码中使用空格,否则难以阅读。当变量不会改变时,也使用 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}`)
})