Chrome扩展程序:向使用Cookie凭据(CORS)发送的node.js服务器发出http请求

我一直有一些与我的node.js服务器的问题。 我使用heroku启动它,现在我想要我的Chrome扩展发送http请求到服务器(使用cookie)。

我正在使用express.js作为后端,并且无法正确设置CORS。

这是我在app.js中的:

if (process.env.NODE_ENV !== 'production') { app.use(cors({ credentials: true, origin: ['http://localhost:4200', 'http://localhost:8000', 'chrome-extension://kdfekbilmpafgiocanhihiogknfilcio'] })); } else { app.use(cors({ credentials: true, origin: ['chrome-extension://kdfekbilmpafgiocanhihiogknfilcio'] })); } app.use(session({ secret: 'angular shhh secret auth', resave: true, saveUninitialized: true, cookie : { httpOnly: true, expires: new Date(253402300000000) } })); 

我正在从我的Chrome扩展(客户端)请求这样的:

 signUp(user) { const options = { withCredentials: true }; return this.myHttp.post(`${this.BASE_URL}/signup`, user, options) .toPromise() .then((result) => { result.json() }); } 

Aaand这是我的错误:

 XMLHttpRequest cannot load https://moodflowextension.herokuapp.com/loggedin. The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'http://localhost:4200' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute. 

我知道我应该以某种方式通过标头中的cookie

会话和证书需要在头部没有通配符的forms下具有更高的安全性。

幸运的是,有一个解决方法。

var whitelist = [/yourDomain/]; var corsOptions = { origin: whitelist }; app.use(cors(corsOptions));

这将使CORS只允许包含yourDomain(这是一个正则expression式btw,而不是一个string)的来源,而不会破坏凭据和会话。