【问题标题】:CORS Response for preflight has invalid HTTP status code 401预检的 CORS 响应具有无效的 HTTP 状态代码 401
【发布时间】:2018-07-01 21:50:25
【问题描述】:

当我向跨服务器发送 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);
        }
}

【问题讨论】:

    标签: nginx phalcon


    【解决方案1】:

    看完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 上的固定问题

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 那么你必须在 ajax 中使用 crossOrigin:true
      猜你喜欢
      • 2017-03-15
      • 2017-07-02
      • 2023-04-10
      • 2018-10-02
      • 1970-01-01
      • 2018-09-30
      • 2018-06-17
      • 2016-11-14
      • 2016-09-16
      相关资源
      最近更新 更多