请告诉我如何使用post请求声明到达服务器的变量(节点js)。现在我使用这些代码并获得以下内容:
name=Test&ip=192.168.0.1我如何声明一个变量并为其赋值,如下所示:
var name = "Test";
var ip = "192.168.0.1";我使用的代码:
var http = require("http");
http.createServer(function(request, response){
if (request.method === 'POST') {
let body = '';
request.on('data', chunk => {
body += chunk.toString(); // convert Buffer to string
});
request.on('end', () => {
console.log(body);
});
}
response.end()
}).listen(3000);发布于 2020-03-31 19:19:22
这很容易使用URLSearchParams
const http = require("http");
http.createServer(function(request, response){
// only post is allowed
if (request.method !== 'POST') {
response.end()
return
}
let body = '';
request.on('data', chunk => {
body += chunk.toString()
})
request.on('end', () => {
const params = new URLSearchParams(body)
let name = params.get("name")
let ip = params.get("ip")
response.write(JSON.stringify({
name,
ip
}))
response.end()
})
}
}).listen(3000)我使用JSON.stringify将其插入到一个简单的包装器中,以便使用简单的json返回响应。
当然,没有输入验证等等.
https://stackoverflow.com/questions/60957975
复制相似问题