I want to Upload Image in backened from frontend....I'll use ngFileUploader bower Component.
My frontend code is:
function SampleController(SampleData,Upload,$http) {
var vm = this;
vm.uploadFiles = function(files, errFiles) {
Upload.upload({
url: "localhost:5000/upload", //webAPI exposed to upload the file
data: {
file: files
}
}).then(function(resp) {
console.log(resp)});
}
And i'll added ngf-select in its html file.
And it will show the error--
XMLHttpRequest cannot load localhost:5000/upload. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.
How can I resolved it??
you need to add this:
header('Access-Control-Allow-Headers: Content-Type');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Origin: *');
My project backend is laravel. So, I included this in Route file.
Add cors filter to your application as a middleware
var app = require('express')();
app.use((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', 'PUT', 'POST', 'DELETE']);
next();
});
I would recommend you white list the origins you would allow.
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.
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.
I've seen several questions and answers around this and mine is half working.
I have a node.js api server with url api.domain.com and the website on an nginx server at www.domain.com when I do the following in angular the request goes through on the api server, I see the request I see it getting parsed and put into the database. However, on the client side I do not get a return right away and then eventually I will see No 'Access-Control-Allow-Origin' header is present on the requested resource.
I know what is causing this behavior but shouldn't it throw the error before it hits the API server? Also note that the node.js server has cors enabled. The response that should be coming back is json.
$http({
method: 'POST',
url: "http://api.domain.com/addtrans/" + $scope.accountID,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST, GET, OPTIONS, PUT',
'Content-Type': 'application/x-www-form-urlencoded'
},
transformRequest: function (obj) {
var str = [];
for (var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
data: {
payload: JSON.stringify(trans)
}
}).success(function (result) {
$scope.trans = {};
console.log(result);
});
I have used the below middleware for all of our projects and it has been proven to work best.
const allowCors = (req, res, next) => {
/** Allow all origins, for now TODO */
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Credentials', true);
res.header('Access-Control-Allow-Headers', 'Authorization, Content-Type');
res.header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE');
/** Browser check for pre-flight request to determine whether the server is webdav compatible */
if ('OPTIONS' == req.method) {
res.sendStatus(204);
}
else next();
};
// Put this code before the routes you want to allow CORS to
app.use(allowCors);
You should change the Allow-Origin to something more restricted for security reasons.
The above code covers CORS as well as pre-flight on most browsers(this ia major issue we were having in the beginning).
i used this a while ago (express 3.x):
// npm install --save cors
var express = require('express');
var cors = require('cors');
var app = express();
app.use(cors());
app.use(express.static());
app.get('*', function(){});
require('http').createServer(app).listen(3000)
Remember that the cors header should be on the response which is coming from server not the request which is sent from client.
You can use a middleware to enable cors on the server:
//CORS middleware
var allowCrossDomain = function(req, res, next) {
res.header('Access-Control-Allow-Origin', 'example.com');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
}
//...
app.configure(function() {
...
app.use(allowCrossDomain);
...
});
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 am working on api, which runs as Express JS app, and I am using Angular JS to send requests to that api.
The api requires authorization send in header and I am struggling to do that in angular.
My Express JS code:
app.all('*', function(req, res, next) {
// add details of what is allowed in HTTP request headers to the response headers
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS');
res.header('Access-Control-Allow-Credentials', true);
res.header('Access-Control-Max-Age', '86400');
res.header('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept');
// the next() function continues execution and will move onto the requested URL/URI
next();
});
app.use(function(req, res, next) {
var header=req.headers['authorization']||'', // get the header
token=header.split(/\s+/).pop()||'', // and the encoded auth token
auth=new Buffer(token, 'base64').toString(), // convert from base64
parts=auth.split(/:/), // split on colon
username=parts[0],
password=parts[1];
r(header);
r(token);
r(auth);
r(username);
r(password);
if(username=='usr' && password=='pwd'){
next();
}else{
res.set('WWW-Authenticate', 'Basic realm="Birds.cz login"');
res.status(401).send({error:'auth'});
}
}
When I use curl to send this: curl --user usr:pwd http://127.0.0.1:8000/v1/login, the console prints:
Basic dXNyOnB3ZA==
dXNyOnB3ZA==
usr:pwd
usr
pwd
which is correnct.
My angular service looks like this:
function testLogin() {
$http({
method :'GET',
url:'http://127.0.0.1:8000/v1/login',
}).success(function(data, status, headers, config) {
alert(data);
}).error(function(data, status, headers, config) {
alert('error');
}).catch(function(error){
alert('catch' + JSON.stringify(error));
});
}
and in config of the whole angular app I have:
.config(function($stateProvider, $urlRouterProvider, $httpProvider) {
//Enable cross domain calls
$httpProvider.defaults.headers.common['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
// insert authorization header
var string = 'usr:pwd';
var encodedString = btoa(string);
$httpProvider.defaults.headers.common['Authorization'] = 'Basic ' + encodedString;
...
}
When I make request from Angular, the node js console prints five empty lines, therefore the Authorization header was not recognized at all.
Any ideas what is the problem?
EDIT When I use Authorization in http request header, the server returns error 0, but when I omit it, it returns error 401, as it should. It seems to me, that providing Authorization header breaks the code on server side before it sends the 401 error code.
EDIT 2 When I log the request header in node js app, it does not show token Authorization at all
{ host: '127.0.0.1:8000',
'user-agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:38.0) Gecko/20100101 Firefox/38.0',
accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'accept-language': 'cs,en-US;q=0.7,en;q=0.3',
'accept-encoding': 'gzip, deflate',
origin: 'http://localhost',
'access-control-request-method': 'GET',
'access-control-request-headers': 'authorization',
connection: 'keep-alive' }
EDIT 3 here is header of request, captured in firebug
Accept text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding gzip, deflate
Accept-Language cs,en-US;q=0.7,en;q=0.3
Access-Control-Request-He... authorization
Access-Control-Request-Me... GET
Connection keep-alive
Host 127.0.0.1:8000
Origin http://localhost
User-Agent Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:38.0) Gecko/20100101 Firefox/38.0
Allow requests to come from different domains, add this code at server side to tackle CORS related error -
var resolveCrossDomain = function(req, res,next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header("Access-Control-Allow-Headers", "Content-Type, Authorization");
res.header("Access-Control-Allow-Credentials", true);
if ('OPTIONS' == req.method) {
res.send(200);
}
else {
next();
}
};
app.use(resolveCrossDomain);