【发布时间】:2018-04-11 07:34:03
【问题描述】:
我在 Symfony 3 中使用 FOSrestBundle 和 NelmioCORSBundle 构建了一个 api。
在我的控制器中,我有一个 postSaveLotteryAction() 方法,它将 fosrest 转换为路线 /lotteries/saves/lotteries
现在我的 ReactJS 应用程序使用 Axios 向 api(托管在不同域上)发出 xhr (ajax) 请求,并且由于 CORS,它首先发出一个 OPTIONS 请求。 我的 apache 服务器已正确配置正确的标头,如下所示。
Symfony 显示的消息是 405 method not allowed。但是所有指向 OPTIONS 方法的东西都是允许的。
Access-Control-Allow-Headers: x-requested-with, Content-Type, origin, authorization, accept, client-security-token
Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE, PUT
Access-Control-Allow-Origin: *
Access-Control-Max-Age: 1000
Allow:
Connection: Keep-Alive
Content-Length: 250
Content-Type: text/html; charset=iso-8859-1
Date: Wed, 11 Apr 2018 07:03:30 GMT
Keep-Alive: timeout=2, max=100
Server: Apache/2
Accept: */*
Accept-Encoding: gzip, deflate
Accept-Language: nl-NL,nl;q=0.9,en-US;q=0.8,en;q=0.7
Access-Control-Request-Headers: content-type
Access-Control-Request-Method: POST
Connection: keep-alive
Host: api.naamloting.nl
Origin: http://beta.naamloting.nl
这是我的 bin/console d:r 输出,我在 route.yml 中添加了 GET、OPTIONS、POST 方法。
get_lottery GET|POST|OPTIONS ANY ANY /lotteries/{uuid}
get_lottery_stats GET|POST|OPTIONS ANY ANY /lottery/stats
post_lottery_save_lottery GET|POST|OPTIONS ANY ANY /lotteries/saves/lotteries
get_lottery_image GET|POST|OPTIONS ANY ANY /lotteries/{nameOfWinner}/image
get_lottery_ticket GET|POST|OPTIONS ANY ANY /lotteries/{nameOfWinner}/ticket
这也是我的 config.yml(部分),因此可以更清楚地看到可能导致它的原因。
# Nelmio CORS
nelmio_cors:
defaults:
allow_origin: ['*']
allow_methods: ["POST", "PUT", "GET", "DELETE", "OPTIONS"]
allow_headers: ["content-type"]
max_age: 3600
paths:
'^/lottery': ~
'^/lotteries': ~
# FOS REST Bundle
fos_rest:
body_listener: true
param_fetcher_listener: true
view:
view_response_listener: 'force'
formats:
jsonp: true
json: true
xml: false
rss: false
mime_types:
json: ['application/json', 'application/x-json']
jpg: 'image/jpeg'
png: 'image/png'
jsonp_handler: ~
routing_loader:
default_format: json
include_format: false
format_listener:
rules:
- { path: ^/, priorities: [ json, jsonp ], fallback_format: ~, prefer_extension: true }
exception:
enabled: true
exception_controller: 'fos_rest.exception.controller:showAction'
【问题讨论】:
标签: symfony cors fosrestbundle nelmiocorsbundle