javascript - 我尝试使用 await fetch 向节点 js 请求 body json 是空的
问题描述
我是节点 js 的新手,所以我尝试使用以下代码请求获取 json 帖子到节点 js:
const req = await fetch(
"http://localhost:3000/api/auth/signin", {
method: "POST",
header:{
'Accept':'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
username:myusername,
password:mypassword
})
},
)
但是当我在服务器端检查身体是空的,我错过了什么吗?
这是我的服务器端代码:
exports.signin = (req, res) => {
db.findByUsername(req.body.username,(err,data) =>{
if(err){
if (err.kind === "not_found") {
res.status(404).send({
message: `Not found customer with username or password.`
});
} else {
res.status(500).send({
message: "Error retrieving Customer with id " + req.body.username
});
}
}
console.log(data)
if(data.password_user != req.body.password){
return res.status(401).send({
accessToken: null,
message: "Invalid Password!"
});
}
});
};
我试图访问,req.body.username
但它是空的。
这是我的路线:
const { verifySignUp } = require("../middleware");
const controller = require("../controllers/auth.controller");
const bodyParser = require('express');
module.exports = function(app) {
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header(
"Access-Control-Allow-Headers",
"x-access-token, Origin, Content-Type, Accept"
);
next();
});
app.use(bodyParser.json());
app.post("/api/auth/signin", controller.signin);
};
这是错误代码:
TypeError: Cannot read property 'password_user' of null
解决方案
首先,您添加中间件的方式是错误的(老实说,我从未见过)。这就是我要解释的内容:
module.exports = function(app) {
app.use(function(req, res, next) {
// CORS handler
});
app.use(bodyParser.json());
app.use('/api/auth/signin', controller.signin);
};
另请注意您的导入错误的事实:
const bodyParser = require('body-parser');
如果我理解正确,您想修补您的app
这是一个快速应用程序的实例。在这种情况下,您应该在添加任何处理程序和请求body-parser
之前添加中间件。否则,执行顺序是错误的,请求中的原始正文永远不会被解析,因此是.POST
PUT
req.body
undefined
编辑
如果您想body-parser
用于单个路线,您可以尝试以下方法:
app.route('/path/to', bodyParser.json(), function(req,res,next) { });
推荐阅读
- node.js - React 应用程序应该直接与 cognito 通信,或者更好地在两者之间设置后端服务
- javascript - 使用 Puppeteer 下载文件时 Chrome 下载错误
- php - php localtime() 函数返回 UTC 时间而不是本地时间
- java - Java 代码在 NetBeans 中不间断地运行 (setDefaultCloseOperation)
- c - 如何在 C 中为跨平台应用程序着色输出
- json - Json4s杰克逊读写案例类不相等
- javascript - 预期的间谍导航已被调用
- python - CreateView 不保存表单 Django
- kubernetes - Pod 之间的通信
- r - Bookdown - 指定 MathJax URL?