javascript - 允许使用 Express JS 和 HTML5 fetch() 进行跨域请求
问题描述
如何允许使用 ExpressJS 服务器和 Javascript 获取跨域请求?我认为这可能是fetch()
来自客户端的问题,因为Access-Control-Allow-Origin: *
它位于响应的标头中。
我添加了这段代码,但它仍然不起作用:
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 的任何内容:
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).
解决方案
You can use the cors middleware https://expressjs.com/en/resources/middleware/cors.html
推荐阅读
- azure - 从 ADF 管道连接到 ADLS 位置时使用服务主体获取访问令牌失败
- javascript - How to Sort Dates, Numbers, Strings from the array of nested JSON objects in Javascript
- c# - Do I have to dispose Realm instances?
- oracle11g - why does error PLS-00122 code occur for my trigger code in ORACLE SQL 11G
- arrays - How to Filter from Json array and get other corresponding values using Karate
- java - How to check if two objects are equal in java?
- javascript - 为什么 momentjs isBetween 函数在 2020 年的表现不如预期
- python - Test django allauth socialAccount creation
- javascript - How to start react-spring animation only on startup
- php - 将 ZipArchive 与 PHP 8 和临时文件一起使用