reactjs - 如何从 Express API 获取 cookie 到 React?
问题描述
我正在开发登录系统。在前端,当我单击登录按钮时,会运行一个函数,该函数使用 axios 进行 API 调用。这是功能
export const startLogin = ({email, password}) => dispatch =>
new Promise((resolve, reject) =>
axios.post(`${USERS_API_BASE_URL}/login`, {
email,
password,
}, {
withCredentials: true,
}).then(res => {
const {token, user} = res.data
dispatch(setAuth({token, user}))
resolve(res.data.token)
}).catch(error =>
reject(error.response ? error.response.data.message : "Check Your Connection. Please try again later")
))
API 是否发送 Cookie? 是的。我已经在 Postman 中使用它并按预期工作。使用 Postman 登录时,我可以转到身份验证保护的路由。这是在后端触发的登录功能
const generateToken = (user, res) => {
const token = jsonWebToken.sign(
{id: user.id},
process.env.JWT_SECRET_KEY,
{
expiresIn: process.env.JWT_EXPIRY
}
);
res
.status(200)
.cookie("token", token, {
httpOnly: true,
expires: new Date(Date.now() + process.env.JWT_EXPIRY * 24 * 60 * 60 * 1000)
})
.json({
status: "Success",
token,
user
})
}
React 中的登录功能是否正常工作
是的,它工作正常。只有当我不使用{withCredentials: true}
. 否则它给了我错误
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8000/api/v1/users/login. (Reason: header ‘content-type’ is not allowed according to header ‘Access-Control-Allow-Headers’ from CORS preflight response
你实施了 CORS 吗? 是的,这是代码
// Creating the express app
const app = express()
app.use(cors({
origin: 'http://localhost:3000',
credentials: true
}))
app.use(cookieParser())
如果我更改 cookieParser 和 cors 的位置,它会给我同样的错误。另外,如果我没有在 cors() 中放置选项,我会得到同样的错误并且不会收到任何 cookie!
我认为问题出在 axios 请求上,但 stackoverflow 上的其他解决方案都没有奏效
解决方案
您是否在 React package.json 中设置了代理属性?如果没有尝试添加以下行:
"proxy": "http://localhost:8000"
推荐阅读
- python - Python:从txt文件中提取的列表作为字符串不被识别为列表
- textbox - 如何在fabric js TextBox中使文本垂直居中
- node.js - 节点 js 和 mongo db atlas 上的 MongoNetworkError
- jquery - 如何使用jQuery将导航菜单垂直居中
- angular - Angular CDK 虚拟滚动 - IE11 中表格中的文本模糊
- swift - 结构测试:可识别与类测试:可识别
- python - 如何使用 python docx2txt 模块从 docx 文件中检索特定部分
- sas - OPEN 中的 Where 子句查找唯一值
- java - 如何在android中自定义firebase应用内消息?
- docker - 如何创建 docker-compose.yml 文件