4
votes

I'm writing an angular application, and i'm trying to connect to our API using the $http service.

$http.post('https://backend-test/***/v001/login', {'userName': 'admin', 'password': 'passtest'}, {headers: {'Accept': 'application/json', 'Content-Type': 'application/json'}}).then(function success(response) {
    console.log(response);
});

However, i keep on getting this error:

XMLHttpRequest cannot load https://backend-test/***/v001/login. Response for preflight has invalid HTTP status code 403

Also it seems to send an OPTIONS request instead of a POST request:

Request Method:OPTIONS

The strange thing is that it is working correctly when i use this tool:

https://www.hurl.it/

Any thoughts?

2
I think you have to put the key params like that $http.post('https://backend-test/***/v001/login', {params : {'userName': 'admin', 'password': 'passtest'}}, {headers: {'Accept': 'application/json', 'Content-Type': 'application/json'}}).then(function success(response) { console.log(response); }); - Pierre-Luc Bolduc
@pbolduc the use of params is not for post requests - charlietfl
server does not appear to be CORS enabled and/or does not seem to be set up to handle OPTIONS preflight requests that browsers will send when making cross domain requests - charlietfl
It will work on hurl.it or Runscope because those are server based clients making the request. They're not required to use CORS like your client-side JS is. - mansilladev

2 Answers

5
votes

I had the same problem. My backend for this is a tomcat server. I solved it by configuring web.xml like this:

<filter>
    <filter-name>CorsFilter</filter-name>
    <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
    <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,Authorization</param-value>
    </init-param>     
</filter>
1
votes

Here, Cors middleware for exressJS (NodeJS)

npm install cors

Code :

var cors = require('cors'),express = require('express');
var app = express(); // defining app using express

app.use(cors()); // **core as middleware**