I want to know how set Access-Control-Allow-Origin in axios post method at reactJS or react-native environment?
I use CORS Add-ons and it works but I want to set it in the header too, I try these ways but none of them does not work.
axios.defaults.headers.post['Access-Control-Allow-Origin'] = '*';
and
let axiosConfig = {
headers: {
'method':'POST',
'X-Requested-With': 'XMLHttpRequest',
'Content-Type': 'application/x-www-form-urlencoded',
'Access-Control-Allow-Origin': '*',
}
};
You need to enable cross origin request at your server end. A snippet of how you can do it using Express would be as follows
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();
});
This would enable all requests to support CORS. Adapt it as per your requirements.
Check this link for more information if you can not change the server.
Related
I have a Node/Express backend and React frontend. When I'm trying to send post request through axios from my react app to the backend, I get an error:
Access to XMLHttpRequest at
'http://localhost:5000/api/user/create-account' from origin
'http://localhost:3000' has been blocked by CORS policy: Request
header field content-type is not allowed by
Access-Control-Allow-Headers in preflight response.
But, I'm using res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept'); Still, I'm getting that error.
Here's the server side code:
const cors = require("cors");
const app = express();
let corsOptions = {
origin: 'http://localhost:3000',
optionsSuccessStatus: 200 ,
credentials: true
};
app.use(cors(corsOptions));
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', 'http://localhost:3000');
res.header('Content-Type', 'application/json;charset=UTF-8');
res.header('Access-Control-Allow-Credentials', true);
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
next();
});
And, this is how I'm making POST request from my frontend:
axios.post("http://localhost:5000/api/user/create-account", data, { withCredentials: true } )
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
P.S: I know there are similar questions on here but I have followed their answers but my problem isn't solved that's why I'm asking this question.
Error : Access to XMLHttpRequest at 'localhost:8080/api/products' from origin 'http://localhost:4200' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
:8080/api/products:1 Failed to load resource: net::ERR_FAILED
Even after adding these in server.js
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");
res.header("Access-Control-Allow-Methods","GET,POST,PUT,DELETE");
next();
});
The problem on the client may be due to the behavior of Browser opting to handle pre-flight CORS. OPTIONS method is used Instead of using GET method. Adding handler for handling OPTIONS is suggested. Here's the code:
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE, OPTIONS');
res.header('Access-Control-Allow-Headers', 'Access-Control-Allow-Origin, Content-Type, Accept, Accept-Language, Origin, User-Agent');
if(req.method === 'OPTIONS') {
res.sendStatus(204);
} else {
next();
}
});
If you are using Angular CLI you may need to enable proxy by adding proxy.conf.json file in angular application root folder with this configuration:
{
"/api": {
"target": "http://localhost:8080",
"secure": false
}
}
While running Angular App include --proxy-config as below or more appropriately edit pacakage.json start script to include the configuration:
ng serve --proxy-config proxy.conf.json
Here is good article on setting up proxy call
Solution 1 :simply use app.use(cors()) .
Solution 2 : app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*"); // update to match the domain you will make the request from
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header("Access-Control-Allow-Headers","GET,POST,PUT,DELETE");
next();
});
I have a React app that is trying to make an axios request to my Express server to find a user in a Mongo database. Before, I built the back-end on Rails and had a gem for CORS, and after trying to configure CORS on the Express side, I can't seem to find a solution. I want to be able to pass in a custom field in headers (i.e. username) so I can use that field to query against my database.
Error I get in browser:
XMLHttpRequest cannot load http://localhost:3000/api/users/test.
Request header field username is not allowed by Access-Control-Allow-Headers
in preflight response.
My Express server has the following CORS set up and my React axios code is attempting to make a request to the server with a param passed into the headers objects, but still getting preflight in response error.
app.use(function(req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Credentials', 'true');
res.setHeader('Access-Control-Allow-Methods', 'GET,HEAD,OPTIONS,POST,PUT,DELETE');
res.setHeader("Access-Control-Allow-Headers",
"Access-Control-Allow-Headers,
Origin,
Accept,
X-Requested-With,
Content-Type,
Access-Control-Request-Method,
Access-Control-Request-Headers,
Authorization")
res.setHeader('Cache-Control', 'no-cache');
next();
});
export const loadAccount = (username) => {
return(dispatch) => {
axios
.get(`${url}/users/test`, {
headers: {username: username}
})
.then(resp => {
dispatch({
type: 'LOAD_ACCOUNT',
account: resp.data
})
})
.catch(errors => {
console.log(errors)
})
}
}
Seems to me like you have to add username as a valid header in your Access-Control-Allow-Headers clause, i.e.:
res.setHeader("Access-Control-Allow-Headers",
"Access-Control-Allow-Headers,
Origin,
Accept,
X-Requested-With,
Content-Type,
Access-Control-Request-Method,
Access-Control-Request-Headers,
Authorization,
username")
res.setHeader('Cache-Control', 'no-cache');
next();
in the nodejs backend i have added this code to the server.js
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();
});
but in angularjs 2 client side in google chrome is throwing this error
XMLHttpRequest cannot load http://localhost:8080/team. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 405.
this is the service code for angular2 i'm using
export class DataService {
// URL to web api
constructor(private http: Http, private _configuration: Configuration,private team:Team) {
//this.actionUrl = _configuration.ServerWithApiUrl;
this.actionUrl = "http://localhost:8080/team";
}
private actionUrl: string;
addData(postData: Team): Observable<Team[]> {
//let body = JSON.stringify({ Team });
this.team = postData;
console.log(this.team);
let body = JSON.stringify({ postData });
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
console.log(body);
return this.http.post(this.actionUrl, body, options)
.map(this.extractData)
.catch(this.handleError);
}
UPDATED:
For your new error message: Angular2 is lower-casing the headers.
Please update your backend to accept content-type too.
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, content-type, Accept");
You cant test post's to this URL: http://posttestserver.com/post.php?dir=anyNameYouWillFind
And can see your posts there: http://posttestserver.com/data/
Browse to year, month, day and anyNameYouWillFind ..
OLD:
you have to prefix your url!!
this.http.get('http://localhost:8080/v1_user/45646/team');
Fixed it by adding this to the backend node.js
// access control --> allowed all origin
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");
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
next();
})
.options('*', function(req, res, next){
res.end();
})
;
I have created an application that is accessing/fetching the data from mongo/node+express, which is on different domain(eg domain_name).
The code for the get function is :
var request = $http({
method: 'GET',
url: 'https://domain_name.users.io/categories/list',
withCredentials: true /* to get the Cookie value generated at server-side */
});
At the express side, have added the following code in order to avoid the CORS issue:
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods","GET,PUT,POST,DELETE,OPTIONS");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header("Access-Control-Allow-Credentials", "true");
For the above, i am getting the following error:
XMLHttpRequest cannot load https://domain_name.users.io/data/list. A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true. Origin 'http://localhost:8100' is therefore not allowed access.
I have checked the API "https://domain_name.users.io/data/list" and there is no issue with it as i can see the data(when hit on browser).
Could someone please help me for the same
Besides * is too permissive and would defeat use of credentials. So use https://domain_name.users.io/data/list rather than you use *.
You can't do like * because this is a part of security and if you want to allow credentials then your Access-Control-Allow-Origin must not use *.
For more please read here.
Must set the headers:
var request = $http({
method: 'GET',
url: 'https://domain_name.users.io/categories/list',
headers:{'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
withCredentials: true /* to get the Cookie value generated at server-side */
});
==============ON Node Side===============
app.use(function(req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type, Authorization, Access-Control-Allow-Origin, Access-Control-Allow-Headers');
next();
});