如何修复:Axios中不允许CORS多源错误

vi4fp9gy  于 2023-03-29  发布在  iOS
关注(0)|答案(1)|浏览(221)

我想在Axios中设置一个get请求并获取一些数据,但我给予了这个错误:不允许CORS多来源
我的后端是WordPress API
这是我的响应头:

HTTP/1.1 200 OK
Server: nginx
Date: Wed, 29 Mar 2023 10:48:56 GMT
Content-Type: application/json; charset=UTF-8
Transfer-Encoding: chunked
Connection: keep-alive
Access-Control-Allow-Origin: *
X-Robots-Tag: noindex
Link: <https://devapi.markazeahan.com/rest/>; rel="https://api.w.org/"
X-Content-Type-Options: nosniff
Access-Control-Expose-Headers: X-WP-Total, X-WP-TotalPages, Link, Link
Access-Control-Allow-Headers: Authorization, X-WP-Nonce, Content-Disposition, Content-MD5, Content-Type
Allow: GET
Access-Control-Allow-Methods: GET
Access-Control-Allow-Credentials: true
Cache-Control: max-age=0
Expires: Wed, 29 Mar 2023 10:48:55 GMT
Vary: Accept-Encoding
Access-Control-Allow-Origin: *
nhhxz33t

nhhxz33t1#

经过多次搜索,我了解到我的问题是这样的:

Access-Control-Allow-Origin: *

在我的应用程序中设置了两次origin
我通过在function.php中输入以下命令解决了我的问题

function my_customize_rest_cors() {
    remove_filter( 'rest_pre_serve_request', 'rest_send_cors_headers' );
    add_filter( 'rest_pre_serve_request', function( $value ) {
        header_remove( 'Access-Control-Allow-Origin' );
        header( 'Access-Control-Allow-Methods: GET' );
        header( 'Access-Control-Allow-Credentials: true' );
        header( 'Access-Control-Expose-Headers: Link', false );

        return $value;
    } );
}
add_action( 'rest_api_init', 'my_customize_rest_cors', 15 );

相关问题