Axios未发送cookie数据,即使withCredentials为true

5

尝试使用React和Express进行请求并发送cookie。请求/响应正常工作,但是cookie未被发送。在客户端:

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,表示无法找到令牌(Token Not Found)。我已经在Express上启用了CORS并使用了cookie-parser。

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'))

授权标头与令牌和Cookie是两种不同的东西。你应该关注的是像下面这样的内容 - https://github.com/axios/axios#global-axios-defaults - goto
@goto1 我明白了,但是为什么 cookies 没有被发送? - user5939597
1
这将取决于你的 cookie 设置方式 - 如果它们是 SameSite cookies,并且你正在进行跨站请求,那可能会成为一个问题。 - goto
@goto1 尝试将其设置为严格和无,但没有改变任何东西。 - user5939597
1个回答

0

输入图像描述 迟到了,但不设置SameSite cookie选项可能会有问题。上面的图像来自Chrome的网络控制台。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接