我想向远程 API 发送 AJAX 请求。
function Gettest(CourseID) {
var param = { "CourseID": CourseID};
param = JSON.stringify(param);
$.ajax({
type: "Post",
url: apiurl + "Course/DelCoursetargetedaudience",
contentType: "application/json; charset=utf-8",
data: param,
dataType: "json",
success: function (data) {
},
error: function (response) {
}
});
};
但我需要在发送请求之前更改原始名称。
请引用下图。
最佳答案
简而言之:你不能。
如 MDN 所述; Origin 是一个“禁止的” header ,这意味着您不能通过编程方式更改它。
您需要配置 Web 服务器以允许 CORS 请求。
要启用 CORS,请将其添加到您的 Web.config
<system.webServer>
<!-- Other stuff is usually located here as well... -->
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
<system.webServer>
或者,在 Global.asax.cs 中
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
/* Some register config stuff is already located here */
}
// Add this method:
protected void Application_BeginRequest()
{
HttpContext.Current.Response.AddHeader
(name: "Access-Control-Allow-Origin", value: "*");
}
}
关于javascript - 如何设置 Origin 请求 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46808011/