简体   繁体   中英

Request from Rest API using axios

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM