当我想从带有 express 的 get 请求中检索会话 cookie 时遇到问题。
我的服务器在端口 8000 上运行,而我的应用程序在端口 3000 上运行。
当我直接访问http://localhost:8000/setcookie和 /getcookie 时,我可以获取和设置 cookie 并且它工作正常。另一方面,当我从http://localhost:3000尝试相同的事情并使用 axios 在端口 8000 上获取或发布请求时,请求中的 cookie 和 signedCookies 为空,我不知道为什么。是不是因为即使我正在侦听并向端口 8000 发送请求,我还是从端口 3000 发送它?
我尝试使用 get 和 post 方法来创建 cookie。它们似乎都不起作用。我有点失落。
我希望我的解释足够清楚,非常感谢!
服务器
const app = express()
const port = process.env.PORT || 8000
app.set("port", port)
const http = require('http').Server(app);
//Body Parser
var urlencodedParser = bodyParser.urlencoded({
extended: true
});
app.use(urlencodedParser);
app.use(bodyParser.json());
//Définition des CORS
app.use(function (req, res, next) {
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Credentials', true);
next();
});
app.use(cookieParser("secret"));
app.get('/setcookie', function (req, res, next) {
// Update views
console.log("connection", req);
var mail = req.body.email
res.cookie('b', 'jefaisuntest', {signed: true, expire : 600000});
// Write response
res.send("cookie sent")
})
app.get('/getcookie', function(req, res) {
var username = req.signedCookies['b'];
console.log("iciiii", req)
if (username) {
return res.send(username);
}
return res.send('No cookie found');
});
const server = http.listen(port, function () {
console.log(`listening on *:${port}`)
})
客户
import axios from 'axios';
const headers = {
'Content-Type': 'application/json'
}
const burl = "http://localhost:8000"
export default {
login : function(email:string, password:string) {
axios.get(burl + '/setcookie')
},
isAuth : function() {
axios.get(burl + '/getcookie')
},
}
@mnesarco 说的是正确的 - 从技术上讲,您正在运行两个不同的服务器,这意味着您在两者之间发送的任何请求都是 CORS 请求。为了在 CORS 请求中共享发送 cookie,您需要将该withCredentials
标志设置为 true:
export default {
login : function(email:string, password:string) {
axios.get(burl + '/setcookie', { withCredentials: true })
},
isAuth : function() {
axios.get(burl + '/getcookie', { withCredentials: true })
},
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句