我尝试获取post req.body值,但当我使用console.log(“express”:“^4.17.1”)时,我一直未定义。我尝试了不使用body parser,但使用body parser,我一直得到相同的结果我在stackoverflow中尝试了所有可用的解决方案,但我一直得到与您在server.js中看到的相同的结果
//jshint esversion:6
const express = require("express");
const bodyParser = require("body-parser");
const _ = require("lodash");
const mongoose = require("mongoose");
const cors = require('cors');
const app = express();
app.use(express.json());
app.use(express.urlencoded({extended:true}));
//app.use(bodyParser.urlencoded({ extended: true }))
//var urlencodedParser = bodyParser.urlencoded({ extended: true })
app.use(express.static("public"));
app.use(cors());
app.get("/", (req, res) =>
{
res.send("Hello");
});
app.post("/login", async (req, res) => {
// const username = req.body.username;
// const password = req.body.password;
const {username , password } = req.body;
console.log("username : " + username);
console.log(req.body);
res.json(username);
});
let port = process.env.PORT;
if (port == null || port == "") {
port = 5000;
}
app.listen(port, function() {
console.log("Server has started Successfully at port " + port);
});
这是 Postman 的要求
localhost:5000/login?username=“salem”&password=1234567
然后使用package.json
{
"name": "server",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Salem",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"express": "^4.17.1",
"lodash": "^4.17.21",
"mongoose": "^5.13.2"
}
}
我希望这能让我对我的问题有一个清晰的认识
向塞勒姆问好
2条答案
按热度按时间6vl6ewon1#
您正在将数据作为查询参数传递
localhost:5000/login?username=“salem”&password=1234567
但是从req.body获取值
const{username,password}=req.body;
您应该使用的是:
ngynwnxp2#
您必须从 Postman 向正文发送用户详细信息,或者您可以使用查询对象从url检索相同的信息。
请参阅req.query