为什么Angular要在POST之前发送Http请求方法:Options ?



我使用Angular Dart V1作为前端框架我正在使用架子&&用于后端API的架子路由器

我正在尝试迁移一些旧的get请求来接受Post Data

老要求:

Future fetchRoutes(FlightPostParamsVO params) async {
  return _http.get(BASE + 'routes').then(handleRoutes);
}

新请求

Future fetchRoutes(FlightPostParamsVO params) async {
    Map post = params.toPostable();
    return _http.post(BASE + 'routes', post ).then(handleRoutes);
  }

我在所有调用的通用响应中设置CORS标头,因为它严格是一个JSON API:

Future<Response> makeResponse( json ) async {
  var response = new Response.ok( json, headers: {'content-type': 'text/json',
                                                  'Access-Control-Allow-Origin': '*',
                                                  'Access-Control-Allow-Headers': "Origin, X-Requested-With, Content-Type, Accept",
                                                  'Access-Control-Allow-Methods': "POST, GET, OPTIONS"} );
  return response;
}

得到404,输出如下:

OPTIONS http://localhost:1234/tickets/routes 404 (Not Found)
(index):1 XMLHttpRequest cannot load http://localhost:1234/tickets/routes. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. The response had HTTP status code 404.

当我检查网络流量时-我所有的GET请求都有正确的报头

当我检查网络流量时-我的POST调用是由一个方法设置为OPTIONS的请求引起的-该调用不包含报头。

我的POST路由处理程序从未被调用

路由器

  Router airRouter = router();
  Router tickets = airRouter.child('/tickets');
  tickets.add('/cities', ['GET'], controller.handleCitites);
  tickets.add('/times', ['GET'], controller.handleTimes);
  tickets.add('/routes', ['POST'], controller.handleRoutes);
  tickets.add('/{id}/tickets/', ['GET'], controller.handleTickets);
  io.serve(airRouter.handler, 'localhost', 1234);

修复症状:

门票。add('/routes', ['OPTIONS'], controller.handleRoutes);

问题:为什么HTTP请求在每个POST之前发送一个请求方法:OPTIONS,什么是只调用POST的正确方法?

这不是角。是浏览器。方法OPTION的第一个请求是测试CORS头,以确保浏览器允许发布。

解决方案:

http://thomaslockerambling.blogspot.com/2014/10/shelf-middleware-adding-cors-headers.html

  • 创建CORS对象并添加到标题
  • 拦截呼叫选项
  • 状态码为200 OK的响应

最新更新