【发布时间】: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