reactjs - React POST 请求是在没有 cookie 的情况下发送的
问题描述
我正在努力处理一个确实想在其标头中发送 cookie 的 Axios POST 请求。
我的 API 路由/search/producers
与 Postman 一起使用:登录后,此路由会以正确的数据回答。
使用axios POST请求,服务器找不到req.user
,因为cookie没有发送。
在我的浏览器中,我总是得到401 OPTIONS
响应。
响应标头:
OPTIONS /search/producers HTTP/1.1
Host: localhost:4242
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:77.0) Gecko/20100101 Firefox/77.0
Accept: */*
Accept-Encoding: gzip, deflate
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type,withcredentials
Referer: http://localhost:3000/home
Origin: http://localhost:3000
Connection: keep-alive
请求标头:
HTTP/1.1 401 Unauthorized
X-Powered-By: Express
Access-Control-Allow-Origin: http://localhost:3000
Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept
Access-Control-Allow-Credentials: true
Access-Control-Allow-Methods: GET, PUT, POST, DELETE, HEAD, OPTIONS
Content-Type: application/json; charset=utf-8
Content-Length: 28
ETag: W/"1c-IxTdph/1tV0PHzy4xuP38jYWJTg"
Date: Thu, 25 Jun 2020 22:26:37 GMT
Connection: keep-alive
这是我的代码服务器端:
检查功能req.user
(使用Passport创建)
function isAuthenticated (req, res, next) {
console.log(req.headers.cookie) // always undefined with Axios request
if (req.user){
return next();
}else{
return res.status(401).json('Denied access')
}
}
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "http://localhost:3000");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header("Access-Control-Allow-Credentials", "true");
res.header("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE, HEAD, OPTIONS");
next();
});
app.use('/search', isAuthenticated, searchRoutes); // OK with Postman POST, blocks with Axios POST
路线本身:
router.post('/producers', function(req, res) {
if (req.body.product) {
Producers.find({productsCategories: {$regex: req.body.product, $options: 'i'}})
.then(result => {
return res.json(result)
})
.catch(error => {
return res.json("Internal Server Error")
})
}
})
我设置了withCredentials: true
客户端:
const instance = axios.create({
withCredentials: true,
})
instance
.post("search/producers", { product })
.then(res => {
...
})
所有“GET”请求都可以正常工作,在请求标头中发送 Cookie。
你能帮我弄清楚我的代码有什么问题或遗漏吗?感谢您的任何想法。
[编辑] 我决定使用 npm 包cors
并且它起作用了:
对于那些感兴趣的人:
const cors = require('cors');
const corsOptions = {
origin: 'http://localhost:3000',
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
credentials: true
}
app.use(cors(corsOptions))
再次感谢你的帮助。
解决方案
我相信它与这个问题有关: https ://github.com/axios/axios/issues/876
将您的 API 调用替换为以下内容
axios({
url: API_BASE + "search/producers",
withCredentials: true
method: "POST",
data: qs.stringify(product),
}).then(response => {
...
});
推荐阅读
- node.js - Blazor Server 与 socket.io 的合作
- windows - 您好,我尝试在 dev-c++ 中运行我的 c 代码并得到以下信息:[错误] 'for' 循环初始声明仅在 C99 或 C11 模式下允许
- web - 如何在 Web 应用程序中集成签名板
- laravel - 如何从多个控制器获取数据到 Laravel Blade 视图中?
- javascript - Glide.js 滑块未在最后一张幻灯片上暂停
- prometheus-alertmanager - AlertManager 队列正在丢弃消息
- android - 导航栏上的黑色条纹 (AOSP)
- html - 如何使 div 适当地扩大和缩小?
- fpga - ISE 设计套件 14.7 中的“目标不支持逻辑根块和符号”错误
- rabbitmq - 无法启动 RabbitMq redentials_obfuscation