即使使用 withCredentials:true,Axios 也不发送 cookie 数据

5 javascript node.js express axios

尝试使用 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
}
Run Code Online (Sandbox Code Playgroud)

服务器端路由:

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'))
    })
})
Run Code Online (Sandbox Code Playgroud)

和中间件验证器:

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()
    })
}
Run Code Online (Sandbox Code Playgroud)

它返回 401 和未找到令牌。我已经在express和cookie解析器上启用了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'))
Run Code Online (Sandbox Code Playgroud)

Tyl*_*les 0

在此输入图像描述参加聚会迟到了,但不设置 SameSite cookie 选项可能会出现问题。上图来自 Chrome 的网络控制台。