【发布时间】:2019-12-14 03:40:04
【问题描述】:
我正在使用 Nginx 作为 Web 服务器,我这样做了
server {
listen 3000;
server_name .*;
#
# Wide-open CORS config for nginx
#
location / {
proxy_pass http://127.0.0.1:3001;
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
#
# Custom headers and headers various browsers *should* be OK with but aren't
#
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
#
# Tell client that this pre-flight info is valid for 20 days
#
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain; charset=utf-8';
add_header 'Content-Length' 0;
return 204;
}
if ($request_method = 'POST') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
}
if ($request_method = 'GET') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
}
}
}
我正在尝试对那个 VM IP 进行 Ajax GET
@extends('layouts.admin.master')
@section('content')
<div class="container-fluid">
<iframe id="test" src="" width="450" height="200" frameborder="0"></iframe>
</div>
@stop
@section('custom-scripts')
<script type="text/javascript">
var url = "http://172.18.57.62:3000/d-solo/tEnKhjQmk/boss-mbn-clients-detailed-info?orgId=1&var-VM_NAME=87d8f990-b538-11e9-a5d9-0050568d9fc1&var-SESSION_NAME=MBN_UE&panelId=2" ;
$.ajax({
type: "GET",
url: url,
xhrFields: {
withCredentials: true,
},
crossDomain: true,
beforeSend: function(xhr, settings){
xhr.setRequestHeader("Authorization","Bearer eyJrIjoidlRmTlg4VnNUdXZ0RktGU2p5UGhwTmtieFN1R1ZyTkoiLCJuIjoiYWRtaW4iLCJpZCI6MX0=");
},
success: function(data){
console.log('%c SUCCESS --', "color: green;");
$("#test").attr('src',url)
$("#test").contents().find('html').html(data);
}, error: function (error) {
console.log('%c ERROR --', "color: red;");
console.log(error);
}
});
</script>
@stop
我一直在得到
从源“http://boss.test”访问“http://172.18.57.62:3000/d-solo/tEnKhjQmk/boss-mbn-clients-detailed-info?orgId=1&var-VM_NAME=87d8f990-b538-11e9-a5d9-0050568d9fc1&var-SESSION_NAME=MBN_UE&panelId=2”处的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:“Access-Control-Allow-Origin”的值' 当请求的凭证模式为 'include' 时,响应中的标头不能是通配符 '*'。 XMLHttpRequest 发起的请求的凭证模式由 withCredentials 属性控制。
【问题讨论】:
-
查看这里:api.jquery.com/jQuery.ajax 并寻找“跨域”(抱歉,没有时间提供更详细的答案)
-
@PeterB 我添加了
xhrFields: { withCredentials: true, },-- 产生相同的结果。
标签: javascript jquery ajax nginx cors