I am not able to run angular application - angularjs

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();
});

Related

I'm getting CORS error: Request header field content-type is not allowed by Access-Control-Allow-Headers

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.

No 'Access-Control-Allow-Origin in reactJS

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.

Allowing CORS from React front end not allowing Express back end to use Bing API

I currently have my front end and back end separate. When I start my React app on localhost:3000 to hit my Express app at localhost:8000/search/results?search_query=, I get blocked by CORS. So I set this in my Express backend's app.js file:
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use('/', index);
app.use('/search', search);
app.use('/results', result);
app.listen(8000, () => {
console.log('App listening on port 8000...')
})
I am calling my back end route from my front end using this function in React:
bingSearch(term) {
fetch('http://localhost:8000/search/results?search_query=' + term)
.then((response) => {
response.json()
.then((json) => {
this.setState({results: json})
})
})
}
I don't get the CORS error after that. However, the route I'm hitting is a route that uses the Bing Web Search API which has a subscription key that I pass in through the header for that GET request. My app, however, just hangs now.
How and where should I be allowing the CORS that will allow my front end to connect to my back end but will not be disrupting my Bing API GET request?
You need to call next() in your middleware.
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
You can read more about it here: https://expressjs.com/en/guide/writing-middleware.html
You can use cors-proxy-server for this. However, it is only good for testing purposes. For production, you need to have server side calls to Bing API. More information is here: https://learn.microsoft.com/en-us/azure/cognitive-services/bing-web-search/bing-web-search-resource-faq.
I think you are having issue with allowed headers with cors, if I am correct, could you try add this with Express:
res.header(
'Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, BING_API_HEADER'
);
So in front end, you will need to set header using the same name as BING_API_HEADER. This will allow you to access the header info from your server. Once you get the header, you can use it to make API calls.

Cross- origin request

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.

Cross orgin error in google chrome for the api call

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();
})
;

Resources