The Access-Control-Allow-Headers request header field is not permitted as per the Access-Control-Allow-Headers directive

When trying to send files to my server using a post request, I encountered the following error:

Error: Request header field Content-Type is not allowed by Access-Control-Allow-Headers.

After researching the issue, I added the necessary headers:

$http.post($rootScope.URL, {params: arguments}, {headers: {
    "Access-Control-Allow-Origin" : "*",
    "Access-Control-Allow-Methods" : "GET,POST,PUT,DELETE,OPTIONS",
    "Access-Control-Allow-Headers": "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With"
}

However, this new configuration resulted in another error message:

Error: Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers

I searched for a solution and found a similar question that was closed before providing a complete answer. Can anyone advise on which headers should be added or removed in this scenario?

Answer №1

I encountered a similar issue myself and after researching on jQuery documentation, I discovered the following:

When making cross-domain requests, using a content type other than

application/x-www-form-urlencoded
, multipart/form-data, or text/plain will prompt the browser to send a preflight OPTIONS request to the server.

Even though the server permits cross-origin requests, if it does not allow Access-Control-Allow-Headers, errors will be thrown. Angular's default content type is application/json, leading to an attempted OPTION request. To address this, either modify Angular's default header or enable Access-Control-Allow-Headers on the server side. Here's an example with Angular:

$http.post(url, data, {
    headers : {
        'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'
    }
});

Answer №2

In the case of sending a POST request, it is crucial for the server receiving the request to include the Access-Control-Allow-Headers header in its response. Simply adding these headers to the client's request will not have any impact. Therefore, it is advised to remove the 'Access-Control-Allow-...' headers from your POST request.

The responsibility lies with the server to explicitly state its acceptance of cross-origin requests and specify which request headers (such as Content-Type) are permitted – this decision cannot be made by the client alone.

Prior to sending the actual 'POST' or 'GET' request, the requester (typically a web browser) may conduct a 'preflight' test by sending an 'OPTIONS' request. This allows the server to respond with 'Access-Control-Allow-...' headers indicating whether the requested headers, origin, and methods are allowed. If permitted, the requester/browser will proceed with sending the intended request.

(side note:) It is worth mentioning that although the Access-Control-Allow-... values usually use '' as a wildcard, there are cases where specific headers must be listed. For instance, an older Android WebView client did not recognize the '' wildcard and required the exact headers to be specified in the server's response to the OPTIONS request.

Answer №3

For those in need of a Java solution to address the same issue, here is some code I put together. Please note that this should only be used for development purposes. [Update] Avoid using the wildcard character *. Instead, consider using localhost if you require local functionality.

public class CustomCORSFilter implements Filter {

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    HttpServletResponse response = (HttpServletResponse) res;
    response.setHeader("Access-Control-Allow-Origin", "my-authorized-proxy-or-domain");
    response.setHeader("Access-Control-Allow-Methods", "POST, GET");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
    chain.doFilter(req, res);
}

public void init(FilterConfig filterConfig) {}

public void destroy() {}

}

Answer №4

To enable the correct header in PHP, use the following code:

header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, X-Requested-With");

Answer №5

To ensure that the POST request is successfully received, the server must include the Content-Type header in its response.

Here are some common headers to include, along with a custom "X_ACCESS_TOKEN" header:

"X-ACCESS_TOKEN", "Access-Control-Allow-Origin", "Authorization", "Origin", "x-requested-with", "Content-Type", "Content-Range", "Content-Disposition", "Content-Description"

Your web server administrator should configure these settings for the server you are sending your requests to.

You may also ask them to make the "Content-Length" header visible.

They will recognize this as a Cross-Origin Resource Sharing (CORS) request and should be familiar with the necessary server configurations.

For more information, please visit:

Answer №6

This code snippet has been tested and proven to work smoothly in a nodejs environment:

xServer.use(function(req, res, next) {
  res.setHeader("Access-Control-Allow-Origin", 'http://localhost:8080');
  res.setHeader('Access-Control-Allow-Methods', 'POST,GET,OPTIONS,PUT,DELETE');
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type,Accept');

  next();
});

Answer №7

If you encounter issues with localhost and PHP, try implementing the following solution:

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Content-Type'); 

To prevent further issues from localhost, make sure to include the following in your front-end code:

{headers: {"Content-Type": "application/json"}}

By doing this, you can eliminate any problems associated with localhost!

Answer №8

When working with Asp Net Core, a quick way to set it up for development is to include the following code in the Configure method of the Startup.cs file:

app.UseCors(options => options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());

Answer №9

Attempting to set the headers in question is tantamount to tampering with response headers, which are exclusively server-side attributes. The responsibility of providing these headers lies solely with the server receiving the request.

There is no justification for setting these parameters on the client side. Allowing such a practice would render permission mechanisms meaningless, as sites could grant permissions they do not own rather than the actual data owners granting them.

Answer №10

In case you encounter this issue while using an express server, a quick fix is to include the following middleware:

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

Answer №11

When testing JavaScript requests for Ionic2 or AngularJS 2 on your Chrome browser, make sure to install the CORS plugin to allow cross-origin requests.

While get requests might work without the CORS plugin, post, put, and delete requests will require it for smooth testing. It's definitely not ideal, but I wonder how people manage without the CORS plugin.

Also, ensure that the JSON response is not returning a status code of 400.

Answer №12

We have encountered a backend issue that needs to be addressed. If you are utilizing the sails API on the backend, you will need to make changes to the cors.js file and specify your parameters in this section.

module.exports.cors = {
  allRoutes: true,
  origin: '*',
  credentials: true,
  methods: 'GET, POST, PUT, DELETE, OPTIONS, HEAD',
  headers: 'Origin, X-Requested-With, Content-Type, Accept, Engaged-Auth-Token'
};

Answer №13

When working with a web service method, I encounter a situation where multiple parameters are being received as @HeaderParam.

To handle these parameters effectively, it is necessary to declare them in the CORS filter in the following manner:

@Provider
public class CORSFilter implements ContainerResponseFilter {

    @Override
    public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {

        MultivaluedMap<String, Object> headers = responseContext.getHeaders();

        headers.add("Access-Control-Allow-Origin", "*");
        ...
        headers.add("Access-Control-Allow-Headers", 
        /*
         * The name of the @HeaderParam("name") should be specified here (as a raw String):
         */
        "name", ...);
        headers.add("Access-Control-Allow-Credentials", "true");
        headers.add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");   
    }
}

Answer №14

The error occurs when the request header field Access-Control-Allow-Origin is not permitted by Access-Control-Allow-Headers.
This indicates that the Access-Control-Allow-Origin field in the HTTP header is not being processed or allowed in the response. To resolve this issue, simply remove the Access-Control-Allow-Origin field from the request header.

Answer №15

To ensure proper access on my server, I made the necessary adjustments to the web.config file:

<system.webServer>
    <httpProtocol>
        <customHeaders>
            <add name="Access-Control-Allow-Origin" value="https://other.domain.com" />
            <add name="Access-Control-Allow-Methods" value="GET,POST,OPTIONS,PUT,DELETE" />
            <add name="Access-Control-Allow-Headers" value="Content-Type,X-Requested-With" />
        </customHeaders>
    </httpProtocol>
<system.webServer>

Answer №16

When encountering an issue with wildcard "*" for Access-Control-Allow-Headers in the web.config, I found a workaround that worked except for Safari and IE:

<add name="Access-Control-Allow-Headers" value="*" />

To address this, I had to manually specify all custom headers in the web.config:

<system.webServer>
    <httpProtocol>
        <customHeaders>
            <add name="Access-Control-Allow-Origin" value="https://somedomain.com" />
            <add name="Access-Control-Allow-Methods" value="GET,POST,OPTIONS,PUT,DELETE" />
            <add name="Access-Control-Allow-Headers" value="custom-header1, custome-header2, custome-header3" />
        </customHeaders>
    </httpProtocol>
<system.webServer>

Answer №17

Solution for running Angular on a different port than the API:

To make it work, I simply included a wildcard "*" in the Cors Options within the webapi builder.

builder.Services.AddCors(options =>
{

    options.AddPolicy(myAllowSpecificOrigins, policy => {
        policy.WithOrigins("https://localhost:4200", "http://localhost:4200");
        policy.WithHeaders("*"); 
    });
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the process behind Express and React Routes when the browser sends an initial GET request?

Embarking on my journey into the realm of React and full-stack development, I find myself in need of guidance on a particular issue that has been eluding me. In my quest to create an app using React and Express, authentication plays a crucial role. My pla ...

The JSON object, which has been converted into a string and sent over the network,

Attempting to set up a websocket server using TypeScript in Node.js, the following code was used: ws.on('message', (msg: string) => { console.log("got message:" + msg); const m = JSON.parse(msg); console.log(m); ...

Tips for validating an EventEmitter from a service

I am new to Angular and Jasmine and I need assistance testing a small piece of code. In my TypeScript file createcustomer.ts, there is a method that triggers a boolean event which is then listened for in another component. I want to test if the event belo ...

What is the best way to create a JavaScript "input" field that only accepts vowel letters?

Is there a way to create an "input" field that only accepts vowel letters? Additionally, I want to ensure that copying and dragging text into the input field will also be filtered out. <div class="field"> <input class="fie ...

Bug in toFixed causing incorrect results

function calculateTaxAndTotalRent(rent) { var phoneCharges = parseFloat($('#phone_charges').val()); phoneCharges = phoneCharges.toFixed(2); rent = parseFloat(rent); rent = rent.toFixed(2); var tax = parseFloat((rent * 15) / 1 ...

REACT performance impacted by slow array filtering

I have a custom listbox feature, where a div holds a vertical list of other div elements. There is also an input field for searching within the list. While it works fine with small data sets, it becomes extremely slow with large amounts of data. In additi ...

jQuery sends ajax success to input type number

I am encountering an issue with the ajax success loading function when using input type number. Interestingly, when I switch the input type to text, it works perfectly fine. However, once I change the input type back to number, the loading ceases. <s ...

Tips for adjusting a web address provided by a user

I have a JavaScript code that prompts the user to input a URL and then appends it to a div. The code is working fine, but now I am trying to add functionality to edit the entered URL by changing the width and height of any iframes before appending them. ...

Retrieve the overall number of job openings from the Github Job API

I have successfully created an Angular application that mirrors the functionality of However, I encountered a limitation where only 50 positions are available per page, To fetch additional jobs beyond the initial 50, I need to append "?page=X" to another ...

jQuery can be used to relocate buttons on a webpage

When the Contact button is clicked, how can I move the Close button below #panel? It's currently fixed in position. Here's my demonstration: https://jsfiddle.net/25u78gff/ jQuery('.sub-menu').addClass('dropdown-menu'); jQ ...

Struggling to transfer a specific row from a grid to a fresh window in extjs

My goal is to send the selected row from a grid panel to a new window when the user clicks the edit button or double-clicks the row. However, I am encountering difficulties in sending the data. Below is the code for my grid panel (List.js): Ext.define(&a ...

Angular 2 repeatedly pushes elements into an array during ngDoCheck

I need assistance with updating my 'filelistArray' array. It is currently being populated with duplicate items whenever content is available in the 'this.uploadCopy.queue' array, which happens multiple times. However, I want to update ...

Modify jQuery to update the background image of a data attribute when hovering over it

Something seems to be off with this topic. I am attempting to hover over a link and change the background image of a div element. The goal is to always display a different picture based on what is set in the data-rhomboid-img attribute. <div id="img- ...

Finding the data type based on the button clicked with javascript: A beginner's guide

I am trying to work with a PHP function that generates dynamically created divisions. Each of these divisions contains a different data type and a button. How can I extract the data type of a division when the user clicks on the submit button using JavaScr ...

What is the most efficient method for storing and retrieving numerous DOM elements as JSON using the FileSystem (fs) Module in Node.js?

Is there a way to efficiently save dynamically added DOM elements, such as draggable DIVs, to a file and then reload them later on? I am looking for the most organized approach to achieve this. ...

Is it true that JavaScript Date.parse doesn't recognize Alaska Timezones?

When using JavaScript's Date.parse, it handles Pacific Time without any issues: Date.parse('June 20 2015 10:22 PDT') However, it encounters issues with Alaska Time: Date.parse('June 20 2015 10:22 AKDT') Does anyone have a relia ...

Incorporate payment processing functionality into your IONIC app by connecting a

Do not flag this question as a duplicate or already answered. If you have knowledge on this subject, please provide an answer. I am attempting to incorporate the payumoney payment gateway into my hybrid app. After following several tutorials, I have resor ...

Executing Datalist's Delete Command through Page Methods Implementation

Recently, I came across an issue with my DataList and Update Panel on my webpage. I noticed a significant delay in response time after incorporating the Update panels... intrigued, I delved deeper into this phenomenon and found some interesting insights in ...

Setting up Karma configuration to specifically exclude nested directories

When unit testing my Angular 2 application using Karma, I encountered an issue with my directory structure: └── src/ ├── index.js ├── index.js.text ├── index.test.js ├── README.txt ├── startuptest.js ...

How do I convert the object value/data to lowercase in JavaScript using underscore for an HTML5 document?

I am working with an array of objects (arr) where each object consists of 3 properties (Department, Categories, ProductTypes). The values for these properties are a mix of upper and lower case. To perform a comparison between arr and a search filter (alrea ...