javascript - Axios 不发送 cookie 数据,即使使用 withCredentials:true
问题描述
尝试使用 React 和 Express 发出请求并发送 cookie。请求/响应工作正常。但是cookies没有被发送。在客户端:
import axios from 'axios'
let endPoint = 'http://192.168.1.135:80'
axios.defaults.withCredentials = true;
export async function SubmitPost(username, title, body, time){
let res = await axios.post(`${endPoint}/posts/create`, {username: username, title: title, body: body, time: time})
return res.data
}
服务器端路由:
router.post('/create', authenticator.authenticate, async (req, res) => {
let post = new Post({
title: req.body.title,
body: req.body.body,
time: req.body.time,
username: req.body.username
})
post.save().then((doc, err) => {
if (err) {
return res.send(Response('failure', 'Error occured while posting', doc))
}
res.send(Response('success', 'Posted Successfully'))
})
})
和中间件身份验证器:
module.exports.authenticate = (req, res, next) => {
const authHeader = req.headers['authorization']
const token = authHeader && authHeader.split(' ')[1]
if (token == null) {
console.log('No authentication token found')
return res.sendStatus(401)
}
jtoken.verify(token, process.env.SECRET, (err, user) => {
if (err) {
console.log(err)
return res.sendStatus(403)
}
req.user = user
next()
})
}
它返回一个带有未找到令牌的 401。我在 express 和 cookie-parser 上启用了 CORS
app.use(cookieparser())
app.use(cors({origin: 'http://localhost:3000', credentials: true}))
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
app.use('/auth', require('./routes/authentication_route'))
app.use('/posts', require('./routes/post_route'))
解决方案
推荐阅读
- c++ - 在 C++ 中使用 <<++ 和 >>++ 运算符
- node.js - 带有 PassportJS 的 Github oAuth 未经过身份验证
- firebase - Firebase 错误:TOO_MANY_TRIGGERS
- ios - 如何根据其内容更新 TableView 及其父 ScrollView 高度
- python - How do I get the face_recognition encoding from many images in a directory and store them in a CSV File?
- laravel - 更新行时无法创建通知
- c++ - 在用户回调期间遇到未处理的异常
- jquery - 菜单仅在一页上不可点击
- computer-science - 根据此代码,这种语言是类型化语言还是非类型化语言?
- recursion - 使用记忆化将递归公式转换为伪代码