【问题标题】:Axios vue.js CORS Error with proxy undefined responseAxios vue.js CORS 错误,代理未定义响应
【发布时间】:2019-12-17 19:08:26
【问题描述】:

我正在尝试通过端口 3000 上的 REST API 使用端口 8080 上的客户端 vueJS GET 数据。这会导致 CORSE 错误。 POST 工作正常。为了解决这个问题,我尝试按照此处https://medium.com/js-dojo/how-to-deal-with-cors-error-on-vue-cli-3-d78c024ce8d3 的描述创建一个代理。

//vue.config.js
module.exports={
  devServer:{
    proxy: {
      '/teams': {
        target: 'http://192.168.70.54:3000',
        ws: true,
        changeOrigin: true,
        secure: false
      }}}}

我想将我的流量重定向到 3000 端口。

//rest.js
function getTeams() {
  var returnVal;
  axios({
    method: 'get',
    url: REST_API + '/teams',
    responseType: 'json'
    })
    .then(function (response) {
      console.log(response.data);  //Is what I want to return
      returnVal = response.data; 
    });
  console.log(returnVal);          //Is undefined
  return returnVal.data;
}

我正在将 response.data 打印到控制台,但我的 returnVal 始终未定义。我错过了什么? 这是我在浏览器中的网络日志。

General:
Request URL: http://localhost:8080/teams
Request Method: GET
Status Code: 200 OK
Remote Address: 127.0.0.1:8080

Response Headers:
Referrer Policy: no-referrer-when-downgrade
access-control-allow-header: Origin, X-Request-With, Content-Type, Accept
access-control-allow-methods: GET, POST
access-control-allow-origin: *
connection: close
content-length: 1070
content-type: application/json
Date: Tue, 17 Dec 2019 18:57:14 GMT

Request Headers:
X-Powered-By: Express
Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Connection: keep-alive
Host: localhost:8080
Referer: http://localhost:8080/setup
User-Agent: Mozilla/5.0 (X11; Linux armv7l) AppleWebKit/537.36 (KHTML, like Gecko) Raspbian Chromium/74.0.3729.157 Chrome/74.0.3729.157 Safari/537.36

【问题讨论】:

  • 您能否确认在then 回调中记录了正确的值?
  • 是的,我在控制台上打印了它。但似乎我不允许返回我的 JSON。

标签: javascript vue.js axios


【解决方案1】:

这个问题有很多内容。

首先,让我们关注这一点:

function getTeams() {
  var returnVal;
  axios({
    method: 'get',
    url: REST_API + '/teams',
    responseType: 'json'
    })
    .then(function (response) {
      console.log(response.data);  //Is what I want to return
      returnVal = response.data; 
    });
  console.log(returnVal);          //Is undefined
  return returnVal.data;
}

第一个日志行记录了正确的值,但第二个日志行是undefined

这是意料之中的。它与 CORS 或代理无关。

问题是 axios 请求是异步的,所以 then 回调直到将来某个时候才会被调用。到那时,函数将返回。您应该会发现出于同样的原因以“错误”的顺序记录了日志行。

您不能从函数同步返回异步检索的值。使用 async/await 可能会让它看起来像你可以,但即使这样也是一种捏造,隐藏了潜在的承诺。

你有两个选择:

  1. 返回来自getTeams 的承诺。这就解决了等待调用代码的问题。
  2. 如果您在组件内部,您可以在then 回调中设置data 属性。这不是返回值。

那么我们有你问题的其他部分。

您似乎已成功配置代理。很难确定,但从您在问题中包含的所有内容来看,似乎工作正常。如果代理不起作用,您将无法在控制台日志记录中获得正确的数据。

但是,您的响应中有很多 CORS 标头。如果您使用的是代理,则不需要 CORS 标头。代理是 CORS 的替代品,您不能同时使用两者。

至于为什么您的 CORS 请求在使用代理之前失败,从问题中提供的信息中很难说。

【讨论】:

  • YES 选项 1 对我有用!您刚刚保存了我们的项目,非常感谢。我现在返回异步。代理也可以正常工作。
猜你喜欢
  • 2021-05-26
  • 1970-01-01
  • 2021-11-02
  • 2019-03-11
  • 2019-08-03
  • 2021-11-16
  • 2020-07-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多