简体   繁体   English

无法从自定义 Rails API 使用 React 访问 response.status

[英]Unable to access response.status with React from a custom rails API

I am trying to get the status of a request I do from a React website I am working on, using axios to fetch make requests to a RoR API I developed.我正在尝试从我正在处理的 React 网站获取我所做的请求的状态,使用 axios 获取对我开发的 RoR API 的请求。 I would like to confirm that the POST request succeeded by accessing the status value from this (which is the output of a console.log(response) :我想通过访问状态值来确认 POST 请求成功(这是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

But when I try a console.log(response.status) all I get is an undefined .但是当我尝试使用console.log(response.status)我得到的只是一个undefined

Here is the code :这是代码:

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]);

I am thinking to change the response from my API, but I really doubt it is the right approach.我正在考虑更改我的 API 的响应,但我真的怀疑这是正确的方法。

Edit 1: adding some complementary code编辑 1:添加一些补充代码

you have to declare the function you give in parameter to useEffect as async to be able to use await inside for your async function handleSignup您必须将在参数中提供给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]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM