I'm struggling with an Axios POST request that does want to send cookie in its headers.
My API route /search/producers is working with Postman : once logged in, this route answers with correct data.
With Axios POST request, the server can not find req.user because the cookie is not sent.
In my browser, I always get a 401 OPTIONS response.
Response headers :
OPTIONS /search/producers HTTP/1.1
Host: localhost:4242
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:77.0) Gecko/20100101 Firefox/77.0
Accept: */*
Accept-Encoding: gzip, deflate
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type,withcredentials
Referer: http://localhost:3000/home
Origin: http://localhost:3000
Connection: keep-alive
Request headers :
HTTP/1.1 401 Unauthorized
X-Powered-By: Express
Access-Control-Allow-Origin: http://localhost:3000
Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept
Access-Control-Allow-Credentials: true
Access-Control-Allow-Methods: GET, PUT, POST, DELETE, HEAD, OPTIONS
Content-Type: application/json; charset=utf-8
Content-Length: 28
ETag: W/"1c-IxTdph/1tV0PHzy4xuP38jYWJTg"
Date: Thu, 25 Jun 2020 22:26:37 GMT
Connection: keep-alive
Here is my code server-side :
The function that checks req.user (created with Passport)
function isAuthenticated (req, res, next) {
console.log(req.headers.cookie) // always undefined with Axios request
if (req.user){
return next();
}else{
return res.status(401).json('Denied access')
}
}
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "http://localhost:3000");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header("Access-Control-Allow-Credentials", "true");
res.header("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE, HEAD, OPTIONS");
next();
});
app.use('/search', isAuthenticated, searchRoutes); // OK with Postman POST, blocks with Axios POST
The route itself :
router.post('/producers', function(req, res) {
if (req.body.product) {
Producers.find({productsCategories: {$regex: req.body.product, $options: 'i'}})
.then(result => {
return res.json(result)
})
.catch(error => {
return res.json("Internal Server Error")
})
}
})
I set up withCredentials: true client-side :
const instance = axios.create({
withCredentials: true,
})
instance
.post("search/producers", { product })
.then(res => {
...
})
All "GET" requests work perfectly, sending the Cookie in request header.
Can you help me to figure out what's wrong or missing in my code please ? Thanks for any idea.
[EDIT] I decided to use npm package cors and it worked :
For those interested :
const cors = require('cors');
const corsOptions = {
origin: 'http://localhost:3000',
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
credentials: true
}
app.use(cors(corsOptions))
Thanks again for your help.
I believe it's related to this issue:
https://github.com/axios/axios/issues/876
replace your API call with the following
axios({
url: API_BASE + "search/producers",
withCredentials: true
method: "POST",
data: qs.stringify(product),
}).then(response => {
...
});
Related
I know that this has been asked so many times, but none of the answers I've found seems to work. My app is React frontend and Flask backend via an api. I have just switched to axios from the usual await fetch and it keeps throwing CORS errors:
Access to XMLHttpRequest at 'http://127.0.0.1:5050/api/user/register' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
My code is thus:
const config = {
headers: {
"Access-Control-Allow-Origin": "*",
"Content-Type": "application/json" ,
},
}
const customFetch = axios.create({
baseURL: 'http://127.0.0.1:5050',
});
export const registerUser = createAsyncThunk(
'user/registerUser',
async (user, thunkAPI) => {
try {
const resp=await customFetch.post('/api/user/register', user, config);
return resp.data ;
}catch (error) {
return thunkAPI.rejectWithValue(error.response.data.msg);
}
}
);
My server has
CORS(app)
now also added:
#app.after_request
def add_security_headers(resp):
resp.headers['Access-Control-Allow-Origin']='*'
resp.headers['Access-Control-Allow-Methods']='GET, POST, PUT, OPTIONS'
resp.headers["Access-Control-Allow-Headers"]="Access-Control-Request-Headers,Access-Control-Allow-Methods,Access-Control-Allow-Headers,Access-Control-Allow-Origin, Origin, X-Requested-With, Content-Type, Accept"
return resp
and in any case it works ok for a standard:
await fetch(`${api_host}/api/user/register`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
data here ...
}),
});
its driving me mad, any clues? Thanks
UPDATE
Just in case there isn't enough info here are the request and response headers:
General
Request URL: http://127.0.0.1:5050/api/user/register
Request Method: POST
Status Code: 500
Referrer Policy: strict-origin-when-cross-origin
Request
POST /api/user/register HTTP/1.1
Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-GB,en;q=0.9,en-US;q=0.8
Access-Control-Allow-Origin: *
Connection: keep-alive
Content-Length: 110
Content-Type: application/json
DNT: 1
Host: 127.0.0.1:5050
Origin: http://localhost:3000
Referer: http://localhost:3000/
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: cross-site
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36 Edg/105.0.1343.27
sec-ch-ua: "Microsoft Edge";v="105", " Not;A Brand";v="99", "Chromium";v="105"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "Windows"
Response
HTTP/1.0 500 INTERNAL SERVER ERROR
Content-Type: text/html; charset=utf-8
X-XSS-Protection: 0
Connection: close
Server: Werkzeug/2.0.0 Python/3.8.10
Date: Fri, 09 Sep 2022 17:52:09 GMT
Once again, any suggestions gratefully received.
I added the following headers server-side, and it seems to have solved it.
I dont know why it stopped working when I switched axios. With standard asyc call it was fine.
resp.headers['Access-Control-Allow-Origin']='*'
resp.headers['Access-Control-Allow-Methods']='GET, POST, PUT, OPTIONS'
resp.headers["Access-Control-Allow-Headers"]="Access-Control-Request-Headers,Access-Control-Allow-Methods,Access-Control-Allow-Headers,Access-Control-Allow-Origin, Origin, X-Requested-With, Content-Type, Accept"
I am using a React frontend to log into a nodejs server running express-session. Frontend is running on localhost:3000, server is on localhost:5000.
Everything is working properly using postman from localhost (session cookie is sent from server when user is properly authenticated and received/stored by postman. Subsequent postman api request to different path on server uses the session cookie and correctly retrieves the data it should based on the session contents). I can also is login using the browser directly to the server (http://localhost:5000/api/authenticate). The server generates the session, sends the cookie to the browser and it stores the cookie locally.
What doesn't work is when I make the api request from within the React app. The server is returning the session cookie but the browser is not storing it. After researching this for the last few days (there are a lot of questions on this general subject), it seems to be an issue with cross site request but I can't seem to find the right set of app and server settings to get it working properly. The cookie is being sent by the server but the browser won't store it when the request from the app.
*** after some additional troubleshooting and research, I've made some updates. My initial XHR request requires a pre-flight and the request and response headers appear to be correct now but still no cookie being stored in browser. More details below the setup ****
Server Setup
var corsOptions = {
origin: 'http://localhost:3000',
credentials: true
};
app.options('*', cors(corsOptions)) // for pre-flight
app.use(cors(corsOptions));
app.use(session({
genid: (req) => {
console.log('Inside the session middleware');
console.log(req.sessionID);
return uuidv4();
},
store: new FileStore(),
secret: 'abc987',
resave: false,
saveUninitialized: true,
cookie: { httpOnly: false, sameSite: 'Lax', hostOnly: false }
}));
app.use( bodyParser.json() );
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, withCredentials, credentials');
next();
});
app.post('/api/authenticate', function(req, res) {
const usernameLower = req.body.username.toLowerCase();
const passwordHash = md5(req.body.password);
connection.query('select USERID from USERS where LOWER(USERNAME)=? && PASSWORD=? ', [usernameLower, passwordHash], function (error, results, fields) {
if (error) {
console.log(error);
req.session.destroy();
res.status(500)
.json({
error: 'Internal error please try again'
});
} else if (results[0]) {
const userId = results[0].USERID;
// setup session data
mySession = req.session;
mySession.user = {};
mySession.user.userId = userId;
res.json(mySession.user);
} else {
console.log('auth failed');
req.session.destroy();
res.status(401)
.json({
error: 'Incorrect email or password'
});
}
});
});
Client setup -- the request is triggered by clicking a submit button in a form
handleSubmit(event) {
event.preventDefault();
axios.defaults.withCreditials = true;
axios.defaults.credentials = 'include';
axios({
credentials: 'include',
method: 'post',
url: 'http://localhost:5000/api/authenticate/',
headers: {'Content-Type': 'application/json' },
data: {
username: this.state.username,
password: this.state.password
}
})
.then((response) => {
if (response.status === 200) {
this.props.setLoggedIn(true);
console.log('userId: '+response.data.userId);
} else {
console.log("login error");
}
})
.catch(error => console.log(error))
}
Below is the response cookie sent to the browser but the browser is not storing it.
{"connect.sid":{"path":"/","samesite":"Lax","value":"s:447935ac-fc08-47c6-9b66-4fa30b355021.Yo5H3XVz3Ux3GjTPVhy8i2ZPJm2RM2RzUnznxU9wBvo"}}
Request headers from XHR request (pre-flight):
OPTIONS /api/authenticate/ HTTP/1.1
Host: localhost:5000
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type
Referer: http://localhost:3000/
Origin: http://localhost:3000
DNT: 1
Connection: keep-alive
Pre-flight server response headers
HTTP/1.1 204 No Content
X-Powered-By: Express
Access-Control-Allow-Origin: http://localhost:3000
Vary: Origin, Access-Control-Request-Headers
Access-Control-Allow-Credentials: true
Access-Control-Allow-Methods: GET,HEAD,PUT,PATCH,POST,DELETE
Access-Control-Allow-Headers: content-type
Content-Length: 0
Date: Fri, 10 Jul 2020 21:35:05 GMT
Connection: keep-alive
POST request header
POST /api/authenticate/ HTTP/1.1
Host: localhost:5000
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0
Accept: application/json, text/plain, */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Content-Type: application/json
Content-Length: 45
Origin: http://localhost:3000
DNT: 1
Connection: keep-alive
Referer: http://localhost:3000/
Server response headers
HTTP/1.1 200 OK
X-Powered-By: Express
Access-Control-Allow-Origin: http://localhost:3000
Vary: Origin
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept
Content-Type: application/json; charset=utf-8
Content-Length: 95
ETag: W/"5f-Iu5VYnDYPKfn7WPrRi2d2Q168ds"
Set-Cookie: connect.sid=s%3A447935ac-fc08-47c6-9b66-4fa30b355021.Yo5H3XVz3Ux3GjTPVhy8i2ZPJm2RM2RzUnznxU9wBvo; Path=/; SameSite=Lax
Date: Fri, 10 Jul 2020 21:35:05 GMT
Connection: keep-alive
I used the "Will it CORS" tool at https://httptoolkit.tech/will-it-cors/ and my request/response headers all seem to be correct but still no cookie stored.
Pre-flight request contains the correct origin
Pre-flight response contains the correct allow-origin and allow-credentials
POST request contains the correct origin and allow-credentials
POST response contains the correct
Appreciate any help to unravel this....
I solved my issues and wanted to post the solution in case others come across this.
To recap, the backend server is nodejs using express. The following setup allows the front-end to accept the cookies which were created on the nodejs server.
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "https://frontendserverdomain.com:3000"); // 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-Credentials", true); // allows cookie to be sent
res.header("Access-Control-Allow-Methods", "GET, POST, PUT, HEAD, DELETE"); // you must specify the methods used with credentials. "*" will not work.
next();
});
The front-end app is based on React and uses axios to make http request. It is hosted at "https://frontendserverdomain.com:3000" which is added to the "Access-Control-Allow-Origin" header in the nodejs setup (see above).
On the front-end, Axios needs the "withCreditials" setting applied.
axios.defaults.withCredentials = true;
With these settings, your app will be able to exchange cookies with the back-end server.
One gotcha for me getting CORS working was to make sure the front-end host is properly added to the back-end servers header "Access-Control-Allow-Origin". This includes the port number if it's specified in your URL when accessing the front-end.
Inn terms of cookie exchange, the "Access-Control-Allow-Credentials" and "Access-Control-Allow-Methods" headers must be set correctly as shown above. Using a wildcard on "Access-Control-Allow-Methods" will not work.
This does not look right:
axios.defaults.headers.common = {
credentials: "include",
withCredentials: true
}
There are no such request headers. Instead credentials is controlled via XHR request.
Use this instead to make sure your client accepts cookies:
axios.defaults.withCredentials = true;
I am trying to add Login with spring security JDBC authentication in spring boot and React. I added cors filter configuration to spring security config file to work with CORS. I can Login with when .csrf().disable() is disabled. but when I try to send same post request with with csrf token i am getting error "Request header field x-xsrf-token is not allowed by Access-Control-Allow-Headers in preflight response".
I tried solutions provided in other questios but it dosen't work for me.
response header
HTTP/1.1 500
Vary: Origin
Vary: Access-Control-Request-Method
Vary: Access-Control-Request-Headers
Access-Control-Allow-Origin: http://localhost:3000
Access-Control-Allow-Credentials: true
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Content-Type: application/json;charset=UTF-8
Content-Language: en-US
Transfer-Encoding: chunked
Date: Sun, 20 Jan 2019 06:23:40 GMT
Connection: close
request header
POST /login HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Content-Length: 81
Access-Control-Allow-Origin: http://localhost:3000
Accept: application/json, text/plain, */*
Origin: http://localhost:3000
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36
Content-Type: application/x-www-form-urlencoded
Referer: http://localhost:3000/login
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Cookie: JSESSIONID=5B64C3749B3DCBBB5072B827D59E8418
form data
username: vk%40gmail.com
password: admin
_csrf: 30955a56-abb5-443a-a029-d6b371f16e5a
I send csrf token to react app like this
CsrfToken token = (CsrfToken)request.getAttribute(CsrfToken.class.getName());
map.put("csrf", token.getToken());
this is Cors filter configuration
#Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("*"));
configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"));
configuration.setAllowCredentials(true);
configuration.setAllowedHeaders(Arrays.asList("authorization", "Cache-Control", "content-type", "xsrf-token"));
configuration.setExposedHeaders(Arrays.asList("xsrf-token"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
This axios POST request
export const addProjectTask = (username,password,csrf,history) => async dispatch => {
axios.post('http://localhost:8080/login',
Qs.stringify({
username: username,
password: password,
}), {
headers: {
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
"X-XSRF-TOKEN": csrf,
// Authorization: 'Bearer ' + csrf,
"Content-Type": "application/x-www-form-urlencoded"
},
credentials: 'include',
})
.then(function (response) {
console.log(response);
history.push("/");
})
.catch(function (error) {
console.log(error);
});
};
what am i doing wrong here?
first of all, I am very very new to react. I am trying to upload a file to my amazon S3 bucket using axios.
I get the signature url correctly but I don't know how to continue.. I tried this but it doesn't work.
The error I get is the following:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://xxx.s3.amazonaws.com/wolves.jpeg?AWSAccessKeyId=xxxxxxxxxx&Content-Type=image%2Fjpeg&Expires=1502773987&Signature=ZXQya8d3xZoikzX6dIbdL3Bvb8A%3D. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
import React, { Component } from 'react'
import Dropzone from 'react-dropzone'
import aws from 'aws-sdk'
import axios from 'axios'
export default class ImageAWS extends Component{
uploadFile(files){
console.log('uploadFile: ')
const file = files[0]
aws.config.update({
accessKeyId: 'xxxxxxxxx',
secretAccessKey: 'xxxxxxxx'
});
var s3 = new aws.S3();
var params = {
Bucket: 'xxx',
Key: file.name,
Expires: 60,
ContentType: file.type
};
s3.getSignedUrl('putObject', params, function(err, signedUrl) {
if (err) {
console.log(err);
return err;
} else {
console.log(signedUrl);
var instance = axios.create();
instance.put(signedUrl, file, {headers: {'Content-Type': file.type}})
.then(function (result) {
console.log(result);
})
.catch(function (err) {
console.log(err);
});
return signedUrl;
}
});
}
render () {
return (
<div>
Images Component
<Dropzone onDrop={this.uploadFile.bind(this)} />
</div>
)
}
}
OPTIONS https://xxbucket.s3.amazonaws.com/wolves.jpeg?
AWSAccessKeyId=xxxxxxxxxxxxxxxxxx&Content-Type=image%2Fjpeg&Expires=1502894764&Signature=FqAccUimhyrLgLBldVy%2Fkyx2Xmc%3D HTTP/1.1
Host: xxbucket.s3.amazonaws.com
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:54.0) Gecko/20100101
Firefox/54.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
Access-Control-Request-Method: PUT
Access-Control-Request-Headers: access-control-allow-headers,access-control-allow-methods,access-control-allow-origin
Origin: http://localhost:8080
Connection: keep-alive
HTTP/1.1 403 Forbidden
x-amz-request-id: 4282B87BA935EF9A
x-amz-id-2: jWOwOQ/7BCzvw1xPmJroOzUBhbCmpfGx5HCPaPUvMoYTFMrlhoG5wN902B1brZ5cjYnKHMLWmpQ=
Content-Type: application/xml
Date: Wed, 16 Aug 2017 14:45:05 GMT
Server: AmazonS3
Content-Length: 514
<?xml version="1.0" encoding="UTF-8"?>
<Error><Code>AccessForbidden</Code><Message>CORSResponse: This CORS request is not allowed. This is usually because the evalution of Origin, request method / Access-Control-Request-Method or Access-Control-Request-Headers are not whitelisted by the resource's CORS spec.</Message><Method>PUT</Method><ResourceType>OBJECT</ResourceType><RequestId>4282B87BA935EF9A</RequestId><HostId>jWOwOQ/7BCzvw1xPmJroOzUBhbCmpfGx5HCPaPUvMoYTFMrlhoG5wN902B1brZ5cjYnKHMLWmpQ=</HostId></Error>
You'll need to add the required CORS headers to your dev server.
Read about CORS. Depending on your development server, search for the proper way to add response headers. Then, add the following headers to every response:
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, PATCH, OPTIONS",
"Access-Control-Allow-Headers": "X-Requested-With, content-type, Authorization"
This will enable to request data from other websites on the web. Make sure you add them to the development version only(I assume you are learning, so that's OK). On production, you'll need to limit the "Access-Control-Allow-Origin": "*", to specific urls.
Further reading:
webpack dev server CORS issue
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
For those who are facing this issue while uploading files from front end,
Go to AWS S3 -> select your bucket -> permission tab -> scroll to last
Under section Cross-origin resource sharing (CORS), edit and drop your configuration
[
{
"AllowedHeaders": [
"Authorization",
"Content-Range",
"Accept",
"Content-Type",
"Origin",
"Range",
"Access-Control-Allow-Origin"
],
"AllowedMethods": [
"GET",
"PUT"
],
"AllowedOrigins": [
"*"
],
"ExposeHeaders": [
"Content-Range",
"Content-Length",
"ETag"
],
"MaxAgeSeconds": 3000
}
]
You can edit this as per your requirements.
Finally, Publish/Save it.
This will resolve your CORS issue.
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);