允许使用Express JS和HTML5 fetch()进行跨域请求 [英] Allowing cross domain requests with Express JS and HTML5 fetch()
本文介绍了允许使用Express JS和HTML5 fetch()进行跨域请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何通过ExpressJS服务器和Javascript的提取来允许跨域请求?我认为客户端的fetch()
可能是个问题,因为Access-Control-Allow-Origin: *
在响应的标题中.
How can I allow cross domain requests with an ExpressJS server and Javascript's fetch? I think this might be an issue with fetch()
from the client because Access-Control-Allow-Origin: *
is in the response's headers.
我添加了以下代码,但仍然无法正常工作:
I added this code but it still doesn't work:
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "localhost:4200"); // update to match the domain you will make the request from
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
我注意到请求标头不包含有关COR的任何内容:
I noticed the request headers don't include anything about COR:
Accept
text/html,application/xhtml+xm…plication/xml;q=0.9,*/*;q=0.8
Accept-Encoding
gzip, deflate
Accept-Language
en-US,en;q=0.5
Cache-Control
max-age=0
Connection
keep-alive
Host
localhost:4200
If-None-Match
W/"2ef-TFWfb4ktmG8ds+qhoRRzEvmkPdY"
Upgrade-Insecure-Requests
1
User-Agent
Mozilla/5.0 (Windows NT 10.0; …) Gecko/20100101 Firefox/68.0
前端代码:
export function createHttpObservable(url: string) {
return Observable.create(observer => {
fetch(url, {mode: 'cors'})
.then(response => {
return response.json();
})
.then(body => {
observer.next(body);
observer.complete();
})
.catch(error => {
observer.error(error);
})
});
}
错误:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:9000/api/courses. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
推荐答案
本地主机URL不正确.请按如下所示进行更改.
The localhost URL is not proper. Please change like below.
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "http://localhost:4200"); // update to match the domain you will make the request from
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
这篇关于允许使用Express JS和HTML5 fetch()进行跨域请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文