[英]how to make an axios get server side call then send to client
I am getting cors issues when I make this request on the client side: 在客户端发出此请求时,我遇到了cors问题:
componentDidMount = () => {
console.log('app loading...');
axios.get('some/random/api').then((res) => {
console.log(res, 'res');
})
}
this is part of my server side code: 这是我的服务器端代码的一部分:
app.use('/', express.static('public'));
axios.get(url, {
"headers": {"Authorization": "Bearer "}
})
.then(response => {
console.log(response)
//I WANT TO SEND THE RESPONSE HERE TO THE REACT CLIENT
})
.catch(err => {
console.log(err)
})
how can I then pick this data up on the client side? 我该如何在客户端获取这些数据?
thanks 谢谢
npm install --save cors
安装cors库: npm install --save cors
const cors = require('cors');
将其导入到您的快递项目中: const cors = require('cors');
Attach cors
to your express app, before routes definitions: app.use(cors())
在路由定义之前将cors
附加到您的express应用: app.use(cors())
const express = require('express') const cors = require('cors') const app = express() app.use(cors()) app.get('/', function (req, res, next) { res.json({msg: 'This is CORS-enabled for a Single Route'}) });
As a quick fix, you can also install this chrome extension 作为快速解决方案,您还可以安装此chrome扩展程序
https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en
However, the long-lasting solution is using the yarn add cors
and adding it to your root file in express js. 但是,持久的解决方案是使用yarn add cors
并将其添加到express js中的根文件中。 as highlighted above by @Artem Mirchenko 正如@Artem Mirchenko所强调的
you need to wrap your server code in a route, as per artem's answer likey so: 根据artem的答案,您需要将服务器代码包装在路由中,因此:
app.get('/some/random/api', function (req, res, next) {
// axios request to other server goes here
axios.get(...)
.then( other_server_response => {
// process other server response if necessary here
res.json({ returned_data: other_server_response });
});
});
edit: now I look at it, I'm not sure this is what you want. 编辑:现在我看,我不确定这是您想要的。 Might just need to call the other service from your client and include cors info. 可能只需要从您的客户处调用其他服务,并包含cors信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.