gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 17:04:43 26 4
gpt4 key购买 nike

大家好,我是 NodeJS 的初学者,无论获取请求中的数据如何,我都无法获取值。它显示错误“无法读取未定义的属性‘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}`);
});

最佳答案

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

关于node.js - req.query 在 nodejs 的 Http.createserver 中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53229309/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com