javascript - 无法使用 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:添加一些补充代码
解决方案
您必须声明您在参数中提供的函数,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]);
推荐阅读
- java - 如何将其他类值传递给 set 方法
- php - jquery的点击事件对我不起作用
- javascript - 如何比较和匹配`incomingArray`多维数组`task items and orders`与referenceArray匹配
- c++ - 在 vscode 中调试 c++ 代码时如何从用户那里获取输入
- python - Python split() 函数说明
- postman - 为什么 Postman 中的简单 json 请求正文不起作用
- swift - 嵌套包依赖模块错误
- javascript - Three.js - 如何设置相对于对象位置和方向的位置?
- reactjs - UPI 付款显示错误“出于安全原因,您不得从您的银行帐户汇款以进行此付款。” 在PhonePe
- base - 根据下拉菜单自动填充字段