我想向远程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) {
}
});
};但在发送请求之前,我需要更改源名称。
请参考下图。

发布于 2017-10-18 18:41:34
简而言之:你不能。
正如在MDN上所描述的,Origin是一个“禁止”的头文件,这意味着你不能通过编程来改变它。
您需要配置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: "*");
}
}发布于 2017-10-18 19:08:42
正如Baksteen所说,您不能在JavaScript中更改此标头的值。您必须编辑您的服务器配置以允许跨域请求。
但是:读完你的评论后,我认为你只需要一个调试和测试的解决方案。
在这种情况下,您可以使用Chrome并使用特殊的不安全参数启动它。如果您将此参数提供给Chrome,它将允许您跨域请求。
不要将这个chrome实例用于测试页面以外的其他事情!
chrome --disable-web-security --user-data-dir我尝试了火狐和Chrome的几个附加组件,但它们在最近版本的浏览器上都不起作用。所以我建议切换到chrome并使用上面的参数来测试你的API调用。
如果您对功能更强大的解决方案感兴趣,则可能需要使用调试代理,如Fiddler from Telerik。您可以编写自定义规则,以便Fiddler在请求离开您的PC之前更改您的标头。但在使用它的所有功能之前,您必须深入研究该工具。这可能很有趣,因为它可以帮助您解决不仅仅是调试问题。
https://stackoverflow.com/questions/46808011
复制相似问题