【问题标题】:Why does Angular send Http Request Method: Options before POST?为什么 Angular 在 POST 之前发送 Http 请求方法:选项?
【发布时间】:2015-08-22 07:29:44
【问题描述】:

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

我正在尝试迁移一些旧的获取请求以接受发布数据

旧请求:

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

修复症状:

tickets.add('/routes', ['OPTIONS'], controller.handleRoutes);

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

【问题讨论】:

    标签: angularjs google-chrome browser


    【解决方案1】:

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

    解决方案:

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

    • 创建一个 CORS 对象并附加到标题
    • 拦截对 OPTIONS 的调用
    • 响应状态码为 200 OK

    【讨论】:

    • 链接已损坏! =(
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-06
    • 2018-08-04
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 2018-09-11
    • 1970-01-01
    相关资源
    最近更新 更多