NodeJS 400错误请求,在post调用中获取数据时

6ljaweal  于 2023-04-20  发布在  Node.js
关注(0)|答案(3)|浏览(277)

我在一个端口3000上运行我的React js Web应用程序。对于节点服务器,我使用4000。
当调用fetch方法时,它返回`400 Bad request'. Error POST http://localhost:4006/auth/admin 400(Bad Request)
react code npm在3000端口启动

fetch('http://localhost:4000/auth/admin',
    { mode: 'no-cors',
      method: "POST",
      body: JSON.stringify({
        username:"admin",
        password:"1234"
      }),
      headers: {
        "Content-Type": "application/json",
        'Accept': 'application/json, text/plain, */*',
        credentials: "omit", //
        // "Content-Type": "application/x-www-form-urlencoded",
    },
    })
    .then((response) => console.log(response));

在4000端口中运行的节点代码

const passport = require("passport");
const route = require("../constants/routeStrings");
const keys = require("../config/keys");
const processStatus = require("../constants/processStatus");

const success = {
  status: processStatus.SUCCESS
};

const failute = {
  status: processStatus.FAILURE
};

module.exports = app => {
  app.post('/auth/admin', passport.authenticate("local"), (req, res) => {
    res.send(success);
  });

};
brqmpdu1

brqmpdu11#

不要将正文字符串化。从

body: JSON.stringify({
  username:"admin",
  password:"1234"
}),

body: {
  username:"admin",
  password:"1234"
},
oipij1gg

oipij1gg2#

400响应由passport引发,因为它无法读取您的参数。您需要告诉您的“node”应用程序在您的实际路由之前解析它们。

// Import body parser, you should read about this on their git to understand it fully
const parser = require('body-parser');
const urlencodedParser = parser.urlencoded({extended : false});

// before your routes
app.use(parser .json());
app.use(urlencodedParser) // This will parse your body and make it available for your routes to use

那就打你的其他电话
此外,请确保您正在发送用户名和密码密钥,否则请阅读有关如何将这些密钥名称更改为其他名称的文档

y53ybaqx

y53ybaqx3#

我忍受了很长时间,但我克服了它扔写这些代码块行。我成功地发送请求到服务器的控制器,希望你的:让它试试

首先定义一个异步函数进行POST请求:

async function _postData(url = '', data = {}) {
    const response = await fetch(url, {
        method: 'POST',
        mode: 'cors',
        cache: 'no-cache',
        credentials: 'same-origin',
        redirect: 'follow',
        referrerPolicy: 'no-referrer',
        headers: {
            "Content-type": "application/json; charset=UTF-8"
        },
        body: JSON.stringify(data)
    });
    
    return response.json();
}

现在创建请求JSON payload:

let requestPayload = {
            propertyName1: 'property value1',
            propertyName2: 'property value23',
            propertyName3: 'property value',
            So on
           }

注意:请求模型将是您所需的模型,即您实际发送的请求有效负载。

现在使用此负载发出请求,包括您的端点URL:

_postData('http://servername/example', requestPayload )
            .then(json => {
                console.log(json) // Handle success
            })
            .catch(err => {
                console.log(err) // Handle errors
            });

100%的工作在我的项目。

相关问题