0

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?

4
  • with that cors setup you're still getting the same cors error you listed in the catch block of axios? Commented Nov 20, 2018 at 20:26
  • yup...exactly the same error and i tried a lot of different configurations for cors, non work 🤷 Commented Nov 20, 2018 at 20:33
  • Are you using authentication in express? If so you need to set "withCredentials: true" in axios in order to tell axios to send the authentication cookie. Commented Nov 20, 2018 at 20:34
  • no, my express configuration is exactly as described in the question... Commented Nov 20, 2018 at 21:13

1 Answer 1

3

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.

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

1 Comment

Wow, that literally solved the problem immediately! thank you so much!

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.