[javascript] No Access-Control-Allow-Origin header is present on the requested resource

I want to access information from same domain but with different port number, To allow this I am adding Access-Control-Allow-Origin with the response header.

Servlet Code:(present on www.example.com:PORT_NUMBER)

String json = new Gson().toJson(list);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.setHeader("Access-Control-Allow-Origin", "*");//cross domain request/CORS
response.getWriter().write(json);

jQuery code:(present on www.example.com)

$.post('http://www.example.com:PORT_NUMBER/MYSERVLET',{MyParam: 'value'}).done(function(data)
{
    alert(data);
});

Several times I am getting this error(in console):

XMLHttpRequest cannot load 'http://www.example.com:PORT_NUMBER/MYSERVLET'
No 'Access-Control-Allow-Origin' header is present on the requested resource.

This error mostly occures first time when $.post gets executed. Second time it allows.

My question is that is there missing in servlet or in jQuery code?

Any suggestion will be appreciated.

Update1

I have changed:

response.setHeader("Access-Control-Allow-Origin", "*");

To:

response.setHeader("Access-Control-Allow-Origin", "http://www.example.com");

Then I am getting this error in console:

XMLHttpRequest cannot load http://www.example.com:PORT_NUMBER/MyServletName
The 'Access-Control-Allow-Origin' whitelists only 'http://www.example.com'
Origin 'http://www.example.com' is not in the list,
and is therefore not allowed access.

[Note: whitelist and origin are same, but still it gives error. It works sometimes, and gives above error sometimes.]

Let me know if you need anymore information.

This question is related to javascript java jquery ajax cors

The answer is


On your servlet simply override the service method of your servlet so that you can add headers for all your http methods (POST, GET, DELETE, PUT, etc...).

@Override
    protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

        if(("http://www.example.com").equals(req.getHeader("origin"))){
            res.setHeader("Access-Control-Allow-Origin", req.getHeader("origin"));
            res.setHeader("Access-Control-Allow-Headers", "Authorization");
        }

        super.service(req, res);
    }

You are missing 'json' dataType in the $.post() method:

$.post('http://www.example.com:PORT_NUMBER/MYSERVLET',{MyParam: 'value'})
        .done(function(data){
                  alert(data);
         }, "json");
         //-^^^^^^-------here

Updates:

try with this:

response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));


I find the solution in spring.io,like this:

    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Allow-Headers", "x-requested-with");

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to ajax

Getting all files in directory with ajax Cross-Origin Read Blocking (CORB) Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource Fetch API request timeout? How do I post form data with fetch api? Ajax LARAVEL 419 POST error Laravel 5.5 ajax call 419 (unknown status) How to allow CORS in react.js? Angular 2: How to access an HTTP response body? How to post a file from a form with Axios

Examples related to cors

Axios having CORS issue Cross-Origin Read Blocking (CORB) Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource How to allow CORS in react.js? Set cookies for cross origin requests XMLHttpRequest blocked by CORS Policy How to enable CORS in ASP.net Core WebAPI No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API How to overcome the CORS issue in ReactJS Trying to use fetch and pass in mode: no-cors