1

I have a setup as the title, with cors npm installed in my nodejs express app. Also, there is a basic authentication enabled on the nginx which is hosting my nodejs app. (The authentication simply requires a 'Authorization' key attached to the headers of of each request).

My nodejs entry file (with cors):

var express = require('express');
var bodyParser = require('body-parser');
var morgan = require('morgan');
var routes = require('./routes');
var cors = require('cors');

var app = express();
var port = process.env.PORT || 3000

app.set('view engine', 'ejs');

app.use('/assets', express.static('./public'))
app.use(bodyParser.json({limit: '50mb'}));
app.use(morgan('dev'));
app.use(cors({
    origin: 'http://localhost:8080',
    credentials: true,
    allowedHeaders: ['Content-Type', 'Authorization']
}));
app.options('*', cors());
routes.init(app);

app.listen(port, function() {
    console.log(`Express running on ${port}`)
})

My vuejs main.js file with vue-resource set up to deal with API calls:

import Vue from 'vue'
import App from './App'
import router from './router'
import VueResource from 'vue-resource'

Vue.config.productionTip = false

Vue.use(VueResource)

if(process.env.NODE_ENV === 'production') {
    Vue.http.options.root = 'http://api.server.net'
    Vue.http.interceptors.push((request, next) => {
        request.headers.set('Authorization', 'Basic xxxxx')
        next()
    })
}

new Vue({
    el: '#app',
    router,
    components: { App },
    template: '<App/>'
})

With the above in place, I'm getting this error "Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource."

A few more observations:

-Calling the API with postman and attaching the authorization key to the request header works. (Understand that postman is not affected by the CORS issue, but just to demonstrate that authorization key works). In postman, however, the response header DOES NOT have ACCESS-CONTROL-ALLOW-ORIGIN key. Same is true when I checked the response header in chrome devtools.

-With chrome dev tools, I noticed also that the request header DOES NOT have the authorization key in it.

Could someone point me to the right direction?

Edit: formatting

1 Answer 1

1

I found the answer (in case anyone else faces a similar issue).

The nginx server running nodejs requires Authorization key in the OPTIONS request, which is the cause behind the problem.

Sign up to request clarification or add additional context in comments.

1 Comment

can you explain how you fixed it?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.