首页 > 解决方案 > 我尝试使用 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

标签: javascriptnode.jsexpress

解决方案


首先,您添加中间件的方式是错误的(老实说,我从未见过)。这就是我要解释的内容:

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之前添加中间件。否则,执行顺序是错误的,请求中的原始正文永远不会被解析,因此是.POSTPUTreq.bodyundefined

编辑

如果您想body-parser用于单个路线,您可以尝试以下方法:

app.route('/path/to', bodyParser.json(), function(req,res,next) { });


推荐阅读