2015-09-23 31 views
2

我的請求顯示在Chrome Network XHR工具上。401 Ajax呼叫到不同域URL時的預檢錯誤

General: 
Remote Address:127.0.0.1:80 
Request URL:http://ws.uvx/app_dev.php/api/venuelogin 
Request Method:OPTIONS 
Status Code:400 Bad Request 

Response Headers: 
view source 
Access-Control-Allow-Headers:x-custom-auth 
Access-Control-Allow-Methods:POST, PUT, GET, DELETE, OPTIONS 
Access-Control-Allow-Origin:http://localhost:8383 
Access-Control-Max-Age:3600 
Cache-Control:no-cache, max-age=604800 
Connection:close 
Content-Encoding:gzip 
Content-Length:52 
Content-Type:text/html; charset=UTF-8 
Date:Wed, 23 Sep 2015 07:59:04 GMT 
Expires:Wed, 30 Sep 2015 07:59:04 GMT 
Server:Apache 
Vary:Accept-Encoding 
X-Debug-Token:8cd64c 
X-Debug-Token-Link:/_profiler/8cd64c 
X-Powered-By:PHP/5.5.10 

Request Headers: 
view source 
Accept:*/* 
Accept-Encoding:gzip, deflate, sdch 
Accept-Language:es-ES,es;q=0.8,en;q=0.6 
Access-Control-Request-Headers:accept, content-type, p 
Access-Control-Request-Method:GET 
Cache-Control:no-cache 
Connection:keep-alive 
Host:ws.uvx 
Origin:http://localhost:8383 
Pragma:no-cache 
Referer:http://localhost:8383/UVox%20Mobile/jwt-demo/venuelogin.html 
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.93 Safari/537.36 

我的Ajax調用:

jQuery.ajax({ 
    url: "http://ws.uvx/app_dev.php/api/venuelogin", 
    type: "GET", 
    headers: { 
     "p": "1441", 
     "Content-type": "application/json" 
    } 
}) 

而且Symfony2的CORS配置:

nelmio_cors: 
    defaults: 
     allow_credentials: false 
     allow_origin: [] 
     allow_headers: [] 
     allow_methods: [] 
     expose_headers: [] 
     max_age: 0 
     hosts: [] 
     origin_regex: false 
    paths: 
     '^/api/': 
      allow_origin: ['*'] 
      allow_headers: ['X-Custom-Auth'] 
      allow_methods: ['POST', 'PUT', 'GET', 'DELETE','OPTIONS'] 
      max_age: 3600 

如果我改變allow_headers: 'X-定製驗證']到allow_headers:[」 *']然後我得到一個500錯誤。

我也嘗試過使用Content-Type:application/octet-stream,如PAW所建議的,OSX應用程序檢查我的API請求。實際上,PAW的這個請求是200 OK。

同時執行CURL我得到200 OK的JSON。

我失蹤了什麼? 非常感謝。

回答

1

首先要檢查的是,您不重寫服務器上的標題(啓用站點的配置)。所以看看它們並評論任何Allow-Origin行。

第二步是在你的應用程序(在我的情況的Symfony):

一)我FOSRESTBundle配置是包括以下行JSON之前的html:

format_listener: 
    rules: 
     - { path: ^/, priorities: [ json, xml, html ], fallback_format: json, prefer_extension: true } 

所以我被迫前綴用.json的url,或者更新下面這行,否則服務器試圖返回一個html,並且因爲我沒有爲它創建一個模板,那麼我得到了一個500錯誤。 b)最後一步是避免在routing.yml中單獨聲明路由,並且將其作爲在一個休息類型路由上使用的控制器上的'手動'fosrestbundle路由註釋。

api_venues: 
    type:  rest 
    resource: Acme\DemoBundle\Controller\Api\VenueController