简体   繁体   English

ExpressJS不同域名-CORS

[英]ExpressJS Different Domain Name - CORS

I am having a challange currently setting the domain for a cookie I am sending with the response from my expressjs implementation but currently it is only setting the IP address of where my expressjs server is at(the end point). 我遇到了一个挑战,目前正在设置我要通过我的expressjs实现的响应发送的cookie的域,但是目前它仅设置我的expressjs服务器所在的IP地址(端点)。

Here is my initial CORS configuration; 这是我的初始CORS配置;

router.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, pwd, email");
next();
});

Here is my res.cookie line inside my authentication part; 这是我的身份验证部分中的res.cookie行;

 res.cookie('token', token, {domain: "localhost", expires: new 
 Date(Date.now() + 600000*100000), httpOnly: true});

When I log in using chrome, very oddly I get the cookie but under the IP address of my expressjs endpoint, lets say " http://88.13.91.0 " so when I refresh I lose it. 当我使用chrome登录时,很奇怪地我得到了cookie,但是在我的expressjs端点的IP地址下,说“ http://88.13.91.0 ”,所以刷新时会丢失它。 I also dont see in the response for the expressjs api the "set-cookie" header in the response, but I do get the cookie. 我也没有在expressjs api的响应中看到响应中的“ set-cookie”标头,但是我确实得到了cookie。 I have cleared the cookie to make sure its coming after attempting to log in so I know its not stale. 我已经清除了cookie,以确保尝试登录后它就会出现,因此我知道它不是陈旧的。 I also have in my fetch call "credentials" set to "include" as documented but no luck. 正如我所记录的那样,在提取调用中,我还将“凭据”设置为“包含”,但是没有运气。

My question is, am I not able to set the domain if its not the same as the endpoint? 我的问题是,如果域与端点不同,我是否无法设置域? My thought is that maybe this is a security issue and as a result blocked because no one should be able to set a cookie for a domain that isn't theres, or maybe I am wrong. 我的想法是,这可能是一个安全问题,因此被阻止,因为没有人应该能够为不存在的域设置Cookie,或者我错了。

Try CORS like this and 像这样尝试CORS,然后

import * as cors from "cors"; 

// or // 要么

const cors = require ('cors');
    app.get("/", function (req, res) {
      res.setHeader("Content-Type", "application/x-www-form-urlencoded");
      res.setHeader("Access-Control-Allow-Origin", "*");
      res.setHeader(
        "Access-Control-Allow-Headers",
        "Origin, X-Requested-With, Content-Type, Accept"
      );

      res.setHeader("Access-Control-Allow-Credentials", true);

add this above all your middleware 将此添加到所有中间件之上

app.use(cors());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM