【问题标题】:Axios POST request fails with error status code 500: Internal Server errorAxios POST 请求失败,错误状态码 500: Internal Server error
【发布时间】:2018-11-29 16:37:44
【问题描述】:

我正在尝试通过 Axios 在本地发送一个带有用户名和密码的 POST 请求。

我正在http://127.0.0.1:5000/login 上部署一个 Flask 应用程序,它处理 /login 路由。 POST 请求失败并出现以下错误

POST http://127.0.0.1:5000/login 500 (INTERNAL SERVER ERROR)
Error: Request failed with status code 500
    at createError (createError.js:16)
    at settle (settle.js:18)
    at XMLHttpRequest.handleLoad (xhr.js:77)

我研究了一下,认为这可能是 CORS 的问题,但情况似乎并非如此,因为我尝试了 Axios GET 请求并且它工作正常(响应记录正确)。这是我的部分代码

axios.get("http://127.0.0.1:5000").then(function(response) {
        console.log(response);
      }).catch(function(error) {
        console.log(error);
      })
axios.post("http://127.0.0.1:5000/login", {
        username: this.state.username,
        password: this.state.password
      }).then(function(response) {
        console.log(response);
      }).catch(function(error) {
        console.log(error);
      })

查看 Chrome DevTools,我可以看到 POST 请求有效负载已正确填充。然后我尝试使用以下代码在 Flask 应用程序中打印出服务器端的密钥,但我什么也没得到,是空的。 (这是预期的,因为 POST 请求失败)

dict = request.form
    for key in dict:
        print('form key '+dict[key])

但是,使用带有相应键和值的 Postman 可以正常工作并返回响应并打印出键(见上文)。失败从何而来?当 GET 似乎工作正常时,为什么 POST 请求会失败?

【问题讨论】:

  • 我遇到了同样的问题。我的后端代码中有语法错误。通过邮递员检查您的请求并确保您的服务器端代码运行正确。

标签: javascript post flask axios internal-server-error


【解决方案1】:

2021 年 2 月。为此浪费了 2 个小时。对互联网上这个著名的图书馆没有太多帮助。

解决方案:

  • 在 catch 块中,error 将始终为 500 internal server error
  • 所以,请使用error.response.data 而不是error

代码:

try {
  let result = await axios.post(          // any call like get
    "http://localhost:3001/user",         // your URL
    {                                     // data if post, put
      some: "data",
    }
  );
  console.log(result.response.data);
} catch (error) {
  console.error(error.response.data);     // NOTE - use "error.response.data` (not "error")
}

更新:

我最终写了一个处理错误的通用函数:

文件:common.app.js

export const errorUtils = {
  getError: (error) => {
    let e = error;
    if (error.response) {
      e = error.response.data;                   // data, status, headers
      if (error.response.data && error.response.data.error) {
        e = error.response.data.error;           // my app specific keys override
      }
    } else if (error.message) {
      e = error.message;
    } else {
      e = "Unknown error occured";
    }
    return e;
  },
};

更多信息:https://github.com/axios/axios#handling-errors

【讨论】:

  • 仍然有效,谢谢!。整个上午都在试图解决这个问题!一旦我正确检查错误,我会在 5 分钟内找到解决方案。
  • 是的,很高兴知道它有帮助。
【解决方案2】:

所以我也遇到了同样的问题,我找到的解决方案是这样的:

let data = JSON.stringify({
  username: this.state.username,
  password: password
});

const response = axios.post(url,data,{headers:{"Content-Type" : "application/json"}});

这个解决方案对我有用。

【讨论】:

    【解决方案3】:

    显然 Axios 不喜欢原始 JSON 对象

    {username: this.state.username, password: password} 
    

    但是将数据传递给 FormData 对象似乎工作得很好!

    【讨论】:

      【解决方案4】:

      工作 2 小时后,我意识到我在正文和数据上犯了一个错误。所以,在 axios 中确保你像这样传递数据。

      async function loadToken(){
        try{
          response = await axios({
            url: ``, 
            headers: {
              'Authorization': '',
              'Content-Type': '',
            },
            data: '',
            method: 'POST'
          });
          let data = response.data;
          return {
            tokenInfo:data,
            timestamp:new Date().getTime()
          }
        } catch(err) {
          console.log("err->", err.response.data)
          return res.status(500).send({ret_code: ReturnCodes.SOMETHING_WENT_WRONG});
        } 
      }
      

      我之前的代码是这样传递数据的,这是错误的

      async function refreshToken(){
        try{
            let headers = {
              authorization: '',
              'Content-Type': ''
            }
            let url =  ``
            let body = {
              grant_type: '',
              refresh_token: global.tokenInfo.refresh_token
            }
            data = await axios.post(url, body, {headers});
            let data = response.data
            console.log(data)
            return {
              tokenInfo:data,
              timestamp:new Date().getTime()
            }
        } catch(err) {
            console.log("err->", err.response)
            return res.status(500).send({ret_code: ReturnCodes.SOMETHING_WENT_WRONG});
        }
      }
      

      只需尝试我的第一个代码,希望能解决您的问题。

      【讨论】:

      【解决方案5】:

      大多数情况下是因为使用了错误的内容类型标题

      打开邮递员并查看“正文”选项卡。在那里您可以找到帖子数据的内容类型。它也可以从“标题”选项卡中访问。应该有一个Content-Type 标头。您通过 POST 请求发送的 data 的正确格式取决于 Content-Type 标头。例如,json 内容类型需要 json(javascript 对象)数据或 form-data 内容类型需要 FormData。

      要在 axios 中设置标题,修改代码如下:

      axios.post("http://127.0.0.1:5000/login", {
              username: this.state.username,
              password: this.state.password
            }, {
              headers: {'Content-Type': 'application/json'}
            }).then(function(response) {
              console.log(response);
            }).catch(function(error) {
              console.log(error);
            })
      

      【讨论】:

        猜你喜欢
        • 2020-05-29
        • 1970-01-01
        • 2020-10-21
        • 1970-01-01
        • 1970-01-01
        • 2020-03-29
        • 2020-01-11
        • 2019-08-15
        • 1970-01-01
        相关资源
        最近更新 更多