Reputation: 310
I created a Rest API using express that connects to mongodb.
It works perfectly with postman.
Then i created a simple web app with vue, and tried to get a response from the api using axios, but i get an error:
Access to XMLHttpRequest at ... has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
i tried using multiple solutions including cors, and setting res.header.
index.js
const app = express()
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.use(bodyParser.json())
app.use('/api', require('./routes/api'))
app.use((err, req, res, next) => {
console.log(err)
res.status(422).send({error: err.message + req.params})
})
app.listen(process.env.port || 4000, () => {
console.log('listening...')
})
vue component
import axios from 'axios'
export default {
data: () => ({
info: 'omg',
}),
mounted() {
axios.get('localhost:4000')
.then(response => (this.info = response))
.catch(error => console.log(error))
},
}
How can i get data from the api?
Upvotes: 0
Views: 1435
Reputation: 6034
You should specify protocol scheme: http://
, your cors settings are not the issue.
axios.get('http://localhost:4000')
Also you requests just localhost:4000
and as I see your server hasn't /
route - you will get 404 error.
Upvotes: 3