我使用Angular Dart V1作为前端框架 我正在使用shelf&& amp;用于后端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);
修复症状:
tickets.add(&#39; / routes&#39;,[&#39; OPTIONS&#39;],controller.handleRoutes);
问题:为什么HTTP请求会在每次POST之前发送请求方法:OPTIONS ,并且只有正确的方式才会调用POST?
答案 0 :(得分:2)
那不是棱角分明的。它的浏览器。方法OPTION的第一个请求是测试CORS头,以确保允许浏览器发布。
<强>解决方案:强>
http://thomaslockerambling.blogspot.com/2014/10/shelf-middleware-adding-cors-headers.html