【发布时间】:2021-02-14 13:48:01
【问题描述】:
我正在尝试使用 JWT 在我的 React 网站上构建一个登录/注册系统。
我设置了一个运行良好的 API。我需要将用户登录流程与服务器集成。
这是我的userSlice -
import { createSlice } from "@reduxjs/toolkit";
export const userSlice = createSlice({
name: "user",
initialState: {
user: null,
},
reducers: {
signup: (state, action) => {
fetch("http://localhost:5000/user/signup", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(action.payload),
})
.then((res) => {
console.log(res.data);
state.user = res.data;
})
.catch((e) => {
console.log(e);
});
},
login: (state, action) => {
fetch("http://localhost:5000/user/login", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(action.payload),
}).then((res) => {
state.user = res.data;
});
},
logout: (state) => {},
},
});
export const { login, logout, signup } = userSlice.actions;
export const selectCount = (state) => state.user.user;
export default userSlice.reducer;
Signup 组件 -
import React, { useState } from "react";
import { useDispatch } from "react-redux";
import { signup } from "../../features/userSlice";
import "./Signup.css";
function Signup() {
const [email, setEmail] = useState("");
const [name, setName] = useState("");
const [password, setPassword] = useState("");
const dispatch = useDispatch();
const signUpHandler = (e) => {
e.preventDefault();
dispatch(signup(name, email, password));
};
return (
<div className="signup">
<h3>Sign Up</h3>
<form method="POST">
<div className="input_area">
<label>Username</label>
<input type="text" onChange={(e) => setName(e.target.value)} />
</div>
<div className="input_area">
<label>Email</label>
<input type="text" onChange={(e) => setEmail(e.target.value)} />
</div>
<div className="input_area">
<label>Password</label>
<input
type="password"
onChange={(e) => setPassword(e.target.value)}
/>
</div>
<button onClick={signUpHandler} type="submit">
Sign Up
</button>
</form>
</div>
);
}
export default Signup;
当我单击注册按钮时,我收到此错误 -
未捕获(承诺中)类型错误:无法在已撤销的代理上执行“设置”
知道是什么导致了错误吗?后端工作正常。
提前致谢。
编辑:
获取后我出现了错误。而不是state.user = res.data 我不得不做state.user = JSON.parse(res.data)
但是在我这样做之后,我得到一个不同的错误,上面写着 -
未处理的拒绝 (SyntaxError):JSON 中位置 0 处的意外标记 u
这是我在 POSTMAN 中得到的响应
【问题讨论】:
标签: javascript node.js reactjs redux jwt