角CORS请求被阻止 [英] Angular CORS request blocked

查看:151
本文介绍了角CORS请求被阻止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将我的Angular应用程序与Express上的简单REST服务器连接.服务器仅发送json数据作为对请求的答复.为了增加对CORS的支持,我使用了npm中的cors模块.在Angular应用上,我按照此问题的说明添加了HttpHeaders:

I am trying to connect my Angular app with a simple REST server on express. The server only sends json data in reply to request. To add CORS support, I used the cors module from npm. On the Angular app, I added HttpHeaders following the instructions from this question: Angular CORS request blocked.

这是我在express中设置cors选项的代码: `

Here is my code in express where I set up the cors Options: `

// async CORS setup delegation
function corsOptsDelegator(req, cb) {
    let opts = {},
        origin = req.header('Origin');
    if(imports.allowedOrigins.indexOf(origin) === 1) opts.origin = true;
    else opts.origin = false;
    opts.optionsSuccessStatus = 200;
    opts.methods = ['POST', 'GET']; // allowed methods
    opts.credentials = true; // for passing/setting cookie 
    opts.allowedHeaders = ['Content-Type', 'Accept', 'Access-Control-Allow-Origin']; // restrict headers 
    opts.exposedHeaders = ['Accept', 'Content-Type']; // for exposing custom headers to clients; use for hash
    cb(null, opts);
}
`

这是我将其添加到全局get处理程序中的方式:

Here's how I added it to the global get handler:

`
app.get('/', cors(corsOptsDelegator), (res, req, nxt) => {
    // only for adding cors on all requests
    nxt();
});
`

这是我设置Angular服务的方式:

Here's how I set up the Angular service:

`

export class ContentGetterService {

  private root: string;
  private corsHeaders: HttpHeaders;
  //private contents: string;

  constructor(private http: HttpClient) {
    this.root = 'http://localhost:8888';
    this.corsHeaders = new HttpHeaders({
      'Content-Type': 'application/json',
      'Accept': 'application/json',
      'Access-Control-Allow-Origin': 'http://localhost:4200'
    });
    //this.contents = '';
   }

  getContent(subs: Array<string>): Observable<IContent> {
    return (() => {
      return this.http.get<IContent>( (() => {
        let r = this.root;
        subs.forEach((s, i, a) => {
          if(i === a.length-1) {
            r += s;
          }
          else {
            if(s !== '/') {
              r += s;
            }
          }
        });
        return r;
      })(), {
        headers: this.corsHeaders
      });

    })();
  }
  }

浏览器警告:Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8888/. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

谢谢.

推荐答案

首先,客户端上的问题是由于Firefox选择处理飞行前CORS的行为所致.代替使用GET方法,使用了OPTIONS方法.从我的代码中可以明显看出,我没有任何用于处理OPTIONS的处理程序.经过一番谷歌搜索后,我在github上看到了这篇文章: Express CORS中间件.使用此代码并对我的客户请求标头进行以下修改,我能够正确地启动并运行它.这是代码:

Firstly, the problem on the client was due to the behavior of Firefox opting in to handle pre-flight CORS. Instead of using GET method,OPTIONS method was used. As it is evident from my code, I do not have any handler for handling OPTIONS. After some googling, I came across this post on github: Express CORS middleware. Using this and making the following modifications to my client request headers, I was able to properly get it up and running. Here's the code:

CORS中间件:

function myCors(req, res, nxt) {
    res.header('Access-Control-Allow-Origin', 'http://localhost:4200');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Access-Control-Allow-Origin, Content-Type, Accept, Accept-Language, Origin, User-Agent');
    if(req.method === 'OPTIONS') {
        res.sendStatus(204);
    }
    else {
        nxt();
    }
}`

将其安装到应用程序实例: app.use(myCors);

Mounting it to the app instance: app.use(myCors);

在Angular客户端服务上:

On the Angular client side service:

this.corsHeaders = new HttpHeaders({
  'Content-Type': 'application/json',
  'Accept': 'application/json',
  'Access-Control-Allow-Origin': 'http://localhost:8888/'
});
// ... adding it to the request
getContent(subs: Array<string>): Observable<IContent> {
return (() => {
  return this.http.get<IContent>( (() => {
    let r = this.root;
    subs.forEach((s, i, a) => {
      if(i === a.length-1) {
        r += s;
      }
      else {
        if(s !== '/') {
          r += s;
        }
      }
    });
    return r;
  })(), {
    headers: this.corsHeaders
  });

})();
}

感谢大家的时间和精力.

Thanks everyone for their time and efforts.

这篇关于角CORS请求被阻止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆