首页 > 解决方案 > 无法使用 React 从自定义 Rails API 访问 response.status

问题描述

我正在尝试从我正在处理的 React 网站获取请求的状态,使用 axios 获取对我开发的 RoR API 的请求。我想通过访问状态值来确认 POST 请求是否成功(这是 a 的输出console.log(response)

Promise { <state>: "pending" }​
<state>: "fulfilled"​
<value>: Object { data: {…}, status: 201, statusText: "Created", … }​​
config: Object { url: "pathname", method: "post", data: "{\"user\":{\"email\":\"lou10@email.com\",\"username\":\"lou10\",\"password\":\"azerty\"}}", … }​​
data: Object { data: {…} }​​
headers: Object { "cache-control": "max-age=0, private, must-revalidate", "content-type": "application/json; charset=utf-8" }​​
request: XMLHttpRequest { readyState: 4, timeout: 0, withCredentials: false, … }
status: 201
statusText: "Created"​​
<prototype>: Object { … }
index.jsx:51:11

但是当我尝试 a 时,console.log(response.status)我得到的只是一个undefined.

这是代码:

import axios from 'axios';
import { BASE_URL } from "./config.js";

const post = async (
  endpoint,
  body = null,
  jwt_token = null,
  header = { "Content-Type": "application/json" }) => {

  let opt = header;
  if (jwt_token){
      opt["Authorization"] = jwt_token
  }

  try {
    const response = await axios.post(BASE_URL + endpoint, body, { headers: opt })
    return response
  } catch (err) {
    console.error(`An error occurred while trying to fetch ${endpoint}. ${err}`);

  }
}

export default post;
const handleSignup = async ({ email, username, pwd }) => {
    let body = {
        user: {
            email: email,
            username: username,
            password: pwd
        }
    };
    return await post("/users", body);
};

useEffect(() => {
    if (passwordCheck === false) {
        console.log("Passwords do not match");
    } else if (passwordCheck === true && userData) {
        const response = await handleSignup(userData);
        console.log(response.status);
        // history.push({ pathname: "/", state: response.status });
    }
}, [passwordCheck, userData]);

我正在考虑更改我的 API 的响应,但我真的怀疑这是正确的方法。

编辑 1:添加一些补充代码

标签: javascriptreactjs

解决方案


您必须声明您在参数中提供的函数,useEffect以便async能够在await内部用于您的异步函数handleSignup

 useEffect(async () => {
if (passwordCheck === false) {
    console.log("Passwords do not match");
} else if (passwordCheck === true && userData) {
    const response = await handleSignup(userData);
    console.log(response.status);
    // history.push({ pathname: "/", state: response.status });
}
}, [passwordCheck, userData]);

推荐阅读