Axios API POST 请求即使在 Postman 中测试后也会返回 307 重定向错误

问题描述 投票:0回答:1

我最近将我的 ReactJS 应用程序不再使用

fetch()
方法进行 API 调用,而是实现了 Axios。我的 API 调用的 URL 之前都可以正常工作,并且能够与我的 MongoDB 数据库正确通信,并且大多数通过 Axios 进行时仍然可以。

但是,我的注册 URL 不断返回

307 internal redirect
响应,并且不发布到我的数据库。

注册请求应返回一个 JSON 对象,其中包含 JWT 令牌或“NA”,具体取决于用户是否已存在于数据库中。通过 Postman 测试时,此 POST 请求在两种情况下都正确返回。

但是,当通过我的 ReactJS 前端进行相同的调用时,没有数据的空白响应会与上述

307 internal redirect
代码一起发送回来。

我目前用于用户注册的 URL 是

http://localhost:3000/register/username/password/ID_number/mobile_number/email/accountnum/college/degree/date/location

The response and URL in Google Chrome dev tools

当前从前端发出API请求的代码。

await axios.post('http://localhost:3000/register/'+this.name+'/'+this.password+'/'+this.ID+'/'+this.phoneNum+'/'+this.email+'/'+this.accountNum+'/'+this.university+'/'+this.courseName+'/'+this.dateOfBirth+'/'+this.area, {})
.then((res) => {
    console.log(res);
})

通过测试,我知道 URL 本身和处理注册的后端控制器方法都可以正常工作,因为它们都是独立工作的。仅当我尝试从前端发送相同的请求时,才会出现此问题。

任何有关可能导致此问题的原因的想法将不胜感激。如果需要,我可以提供任何其他信息。

javascript reactjs express axios http-post
1个回答
0
投票

您将

await
then
一起使用,但也没有在
post
请求中发送任何数据。相反,您发送的是一个空对象:

await axios.post('...', {}) // < await and an empty {}
   .then((res) => {         // < but also .then()
      console.log(res);
})

如果你想使用

async/await
那么只需定义一个函数,如下所示:

const postData = async (data) => {
   try {
       const response = await axios.post('...', data);
       console.log(response.data);
   } catch (error) {
      console.error(error);
   }
};

postData({
   name:'jqueeny', 
   password: 'abc123', 
   email: '[email protected]'
   //...
});

或者如果你想使用

then
块,你可以这样做:

axios.post("...", {
    name:'jqueeny', 
    password: 'abc123', 
    email: '[email protected]'
})
.then((response) => {
  console.log(response);
})
.catch((error) => {
    console.log(error);
});
© www.soinside.com 2019 - 2024. All rights reserved.