CORS预检的响应具有无效的HTTP状态代码401

时间:2018-01-23 06:35:48

标签: nginx phalcon

当我向交叉服务器发送ajax请求时,我收到此错误The 'Access-Control-Allow-Origin' header contains multiple values '*, http://localhost.dev',。这是我的ajax

<script>
$(document).ready(function(){
    $("button").click(function(){
        $.ajax({
            type: 'post',
            contentType: 'application/json',
            url: "https://api.domain.com/api/v1/register/phone",
            headers: {
                'x-api-key': 'abc',
                'partner-id': 'xyz'
            },
            data: JSON.stringify({
              'somedata': 'xyz'
            }),
            success: function(result){
                console.log(result);
            },
            error: function(xhr) {console.log(xhr)}
        });
    });
});

我正在使用Phalcon和nginx作为api.domain。我从http://localhost.dev打电话给ajax。我添加了add_header 'Access-Control-Allow-Origin' 'http://localhost.dev';。这是phalcon代码。

In router.php
$router->add(
'/api/v1/register/phone',
[
    'module' => 'api',
    'controller' => 'phone',
    'action'    => 'index',
]); 
In controller:
class PhoneController extends ControllerBase{

public function indexAction()
{
        $apiKey = $this->request->getHeader('x-api-key');
            return $this->sendJson([
                'status' => 'Unauthorized',
                'message' => $apiKey
            ], 401);
        }
}

2 个答案:

答案 0 :(得分:0)

您的API是在单独的域上,而您的项目是在单独的域上吗?如果是,那么尝试在ajax中添加crossOrigin:true,它可能会解决错误。

答案 1 :(得分:0)

阅读本文http://restlet.com/company/blog/2016/09/27/how-to-fix-cors-problems/后,我通过在nginx中添加这些配置来解决我的问题。

add_header 'Access-Control-Allow-Origin' 'http://localhost.dev';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers: *'

当然,我需要更改'Access-Control-Allow-Origin''http://localhost.dev'进行配置。至少,这是我在localhost.dev上修复的问题