首页 > 解决方案 > 允许使用 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).

标签: javascriptexpress

解决方案



推荐阅读