Rakesh
Rakesh

Reputation: 441

How to set the Origin Request Header

I want to send an AJAX request to a remote API.

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) {
        }
    });
};

But I need to change the origin name, before sending the request.

Please refer to the image below.

enter image description here

Upvotes: 15

Views: 77121

Answers (2)

Baksteen
Baksteen

Reputation: 1325

In short: you cannot.

As described on MDN; Origin is a 'forbidden' header. This means that you cannot change it programatically as browsers do you not allow to set it in your client-side JavaScript code.

You would need to configure the web server to allow CORS requests.

To enable CORS, add this to your 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>

Alternatively, in 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: "*");            
    }
}

Upvotes: 35

Cellcon
Cellcon

Reputation: 1295

Just as Baksteen stated, you cannot change this header value in JavaScript. You would have to edit your server configuration to allow cross origin requests.

But: After reading your comments, I think you need a solution for debugging and testing only.

In that case, you can use Chrome and start it with special unsafe parameters. If you provide this parameters to Chrome, it will allow you cross domain requests.

Do not use this chrome instance for other things than testing your page!

chrome --disable-web-security --user-data-dir

I tried several Add-ons for Firefox and Chrome, but they did not work with recent versions of the browsers. So I recommend to switch to chrome and use the parameters above to test your API calls.


If you are interested in a more powerful solution, you may want to use a Debugging Proxy, like Fiddler from Telerik. You may write a custom rule, so Fiddler changes your headers before the request leaves your PC. But you have to dig into the tool, before you can use all its powers. This may be interesting, because it may help you out on more than just this debugging issue.

Upvotes: 9

Related Questions