【问题标题】:Allowing cross domain requests with Express JS and HTML5 fetch()允许使用 Express JS 和 HTML5 fetch() 进行跨域请求
【发布时间】:2019-08-10 18:18:24
【问题描述】:

如何允许使用 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).

【问题讨论】:

    标签: javascript express


    【解决方案1】:

    【讨论】:

      【解决方案2】:

      本地主机 URL 不正确。请按以下方式更改。

      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();
      

      });

      【讨论】:

      • 我得到的是响应头:Access-Control-Allow-Origin: *
      猜你喜欢
      • 1970-01-01
      • 2023-04-07
      • 2016-09-02
      • 2020-07-22
      • 2012-11-03
      • 1970-01-01
      • 2020-11-16
      • 2015-10-11
      • 2016-03-03
      相关资源
      最近更新 更多