XMLHttpRequest cannot load http://localhost:8080/api/test. Origin http://localhost:3000 is not allowed by Access-Control-Allow-Origin.
I read about cross domain ajax requests, and understand the underlying security issue. In my case, 2 servers are running locally, and like to enable cross domain requests during testing.
localhost:8080 - Google Appengine dev server
localhost:3000 - Node.js server
I am issuing an ajax request to localhost:8080 - GAE server
while my page is loaded from node server. What is the easiest, and safest ( Don't want to start chrome with disable-web-security
option). If I have to change 'Content-Type'
, should I do it at node server? How?
This question is related to
javascript
node.js
ajax
google-chrome
cors
If you got 403 after that please reduce filters in WEB.XML tomcat config to the following:
<filter>
<filter-name>CorsFilter</filter-name>
<filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
<init-param>
<param-name>cors.allowed.origins</param-name>
<param-value>*</param-value>
</init-param>
<init-param>
<param-name>cors.allowed.methods</param-name>
<param-value>GET,POST,HEAD,OPTIONS,PUT</param-value>
</init-param>
<init-param>
<param-name>cors.allowed.headers</param-name>
<param-value>Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers</param-value>
</init-param>
<init-param>
<param-name>cors.exposed.headers</param-name>
<param-value>Access-Control-Allow-Origin,Access-Control-Allow-Credentials</param-value>
</init-param>
</filter>
use dataType: 'jsonp', works for me.
async function get_ajax_data(){
var _reprojected_lat_lng = await $.ajax({
type: 'GET',
dataType: 'jsonp',
data: {},
url: _reprojection_url,
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR)
},
success: function (data) {
console.log(data);
// note: data is already json type, you just specify dataType: jsonp
return data;
}
});
} // function
Hi This is the way to solve CORS problem in node Just add these lines on server "api" side in Node.js(or what ever your server File), befor that make sure to install "cors"
const express = require('express');
const app = express();
app.use(express.json());
var cors = require('cors');
app.use(cors());
I finally got the answer for apache Tomcat8
You have to edit the tomcat web.xml file.
probabily it will be inside webapps folder,
sudo gedit /opt/tomcat/webapps/your_directory/WEB-INF/web.xml
find it and edit it
<web-app>
<filter>
<filter-name>CorsFilter</filter-name>
<filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
<init-param>
<param-name>cors.allowed.origins</param-name>
<param-value>*</param-value>
</init-param>
<init-param>
<param-name>cors.allowed.methods</param-name>
<param-value>GET,POST,HEAD,OPTIONS,PUT</param-value>
</init-param>
<init-param>
<param-name>cors.allowed.headers</param-name>
<param-value>Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers</param-value>
</init-param>
<init-param>
<param-name>cors.exposed.headers</param-name>
<param-value>Access-Control-Allow-Origin,Access-Control-Allow-Credentials</param-value>
</init-param>
<init-param>
<param-name>cors.support.credentials</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>cors.preflight.maxage</param-name>
<param-value>10</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CorsFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
This will allow Access-Control-Allow-Origin all hosts. If you need to change it from all hosts to only your host you can edit the
<param-name>cors.allowed.origins</param-name>
<param-value>http://localhost:3000</param-value>
above code from * to your http://your_public_IP or http://www.example.com
you can refer here Tomcat filter documentation
Thanks
If you're in Google Chrome, try installing this add-on:
If you are using express, you can use cors middleware as follows:
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())
Add this to your NodeJS Server below imports:
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
If you need a quick work around in Chrome for ajax requests, this chrome plugin automatically allows you to access any site from any source by adding the proper response header
I was facing a problem while calling cross origin resource using ajax from chrome.
I have used node js and local http server to deploy my node js app.
I was getting error response, when I access cross origin resource
I found one solution on that ,
1) I have added below code to my app.js file
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
2) In my html page called cross origin resource using $.getJSON();
$.getJSON("http://localhost:3000/users", function (data) {
alert("*******Success*********");
var response=JSON.stringify(data);
alert("success="+response);
document.getElementById("employeeDetails").value=response;
});
I accept @Rocket hazmat's answer as it lead me to the solution. It was indeed on the GAE server I needed to set the header. I had to set these
"Access-Control-Allow-Origin" -> "*"
"Access-Control-Allow-Headers" -> "Origin, X-Requested-With, Content-Type, Accept"
setting only "Access-Control-Allow-Origin"
gave error
Request header field X-Requested-With is not allowed by Access-Control-Allow-Headers.
Also, if auth token needs to be sent, add this too
"Access-Control-Allow-Credentials" -> "true"
Also, at client, set withCredentials
this causes 2 requests to sent to the server, one with OPTIONS
. Auth cookie is not send with it, hence need to treat outside auth.
In router.js just add code before calling get/post methods. It works for me without errors.
//Importing modules @Brahmmeswar
const express = require('express');
const router = express.Router();
const Contact = require('../models/contacts');
router.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
You have to enable CORS to solve this
set it in your response headers like
var http = require('http');
http.createServer(function (request, response) {
response.writeHead(200, {
'Content-Type': 'text/plain',
'Access-Control-Allow-Origin' : '*',
'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE'
});
response.end('Hello World\n');
}).listen(3000);
use a CORS middleware like
var allowCrossDomain = function(req, res, next) {
res.header('Access-Control-Allow-Origin', "*");
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
}
and apply via
app.configure(function() {
app.use(allowCrossDomain);
//some other code
});
Here are two reference links
For PHP, use this to set headers.
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: PUT, GET, POST");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
In case anyone searching for the solution , if you are using express here is the quick solution .
const express = require('express')
const cors = require('cors')
const app = express()
1) install cors using npm npm install cors --save
2) import it [require ] const cors = require('cors')
3) use it as middleware app.use(cors())
for details insatll and usage of cors . That is it, hopefully it works.
router.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "*");
res.header("Access-Control-Allow-Headers", "*");
next();});
add this to your routes which you are calling from front-end. Ex- if you call for http://localhost:3000/users/register you must add this code fragment on your back-end .js file which this route lays.
Source: Stackoverflow.com