【问题标题】:Request from Rest API using axios使用 axios 从 Rest API 请求
【发布时间】:2018-11-20 19:46:03
【问题描述】:

我使用 express 创建了一个连接到 mongodb 的 Rest API。

它与邮递员完美配合。

然后我用 vue 创建了一个简单的 web 应用程序,并尝试使用 axios 从 api 获取响应,但我得到一个错误:

访问 XMLHttpRequest at ... 已被 CORS 策略阻止:跨源请求仅支持以下协议方案:http、data、chrome、chrome-extension、https。

我尝试使用多种解决方案,包括 cors 和设置 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 组件

import axios from 'axios'
    export default {
        data: () => ({
            info: 'omg',
        }),
        mounted() {
            axios.get('localhost:4000')
                 .then(response => (this.info = response))
                 .catch(error => console.log(error))
        },
    }

如何从 api 获取数据?

【问题讨论】:

  • 使用该 cors 设置,您仍然会遇到您在 axios 的 catch 块中列出的相同的 cors 错误?
  • 是的......完全相同的错误,我尝试了很多不同的cors配置,不工作????
  • 您是否在 express 中使用身份验证?如果是这样,您需要在 axios 中设置“withCredentials: true”,以便告诉 axios 发送身份验证 cookie。
  • 不,我的快速配置与问题中描述的完全一样...

标签: javascript node.js express vue.js axios


【解决方案1】:

您应该指定协议方案:http://,您的 cors 设置不是问题。

axios.get('http://localhost:4000')

另外,您只请求 localhost:4000,而我看到您的服务器没有 / 路由 - 您将收到 404 错误。

【讨论】:

  • 哇,这确实立即解决了问题!非常感谢!
猜你喜欢
  • 1970-01-01
  • 2019-09-10
  • 2018-01-09
  • 1970-01-01
  • 2021-10-05
  • 1970-01-01
  • 2020-06-13
  • 2020-12-26
  • 1970-01-01
相关资源
最近更新 更多