Reputation: 53
I'm trying to get a JSON object from one of my sever routes using axios in a react component.
Here's the relevant server code
var express = require('express')
var app = express()
app.use(require('morgan')('combined'))
app.use(require('cookie-parser')())
app.use(require('body-parser').urlencoded({ extended: true }))
app.use(require('express-session')({ secret: 'keyboard cat', resave: true, saveUninitialized: true }))
app.use(passport.initialize())
app.use(passport.session())
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()
})
app.get('/',
function (req, res, next) {
res.send(req.user)
}
)
app.listen(process.env.PORT || 8080)
And here is the relevant axios function request in my component
getUser () {
axios.get('http://localhost:8080/', {mode: 'cors', 'Cache-Control': 'no-cache'})
.then(res =>
res.data
)
.then(user =>
this.setState({
user: user
})
)
.catch(console.error())
}
This code works if I disable Cross-Origin Restrictions in browser development settings (I receive the correct JSON object), but it doesn't work by default as it should. I've tried using this CORS express middleware, manually setting the header mode to "cors" instead of "no-cors", setHeader instead of header in the res.header section, adding 'Access-Control-Allow-Origin' and related headers to my axios request and more. I'm unsure how to fix this issue.
When I don't disable Cross-Origin-Restriction in browser I only ever receive an empty string response, no headers set except sometimes 'content-type' and I receive no error message telling me anything. It goes through with the exact same status code as if it were responding correctly.
Upvotes: 3
Views: 7902
Reputation: 36660
Install the cors middleware at npm
This code then will enable all CORS requests.
var express = require('express');
var cors = require('cors');
var app = express();
app.use(cors());
Upvotes: 5