[英]how to make an axios get server side call then send to client
在客户端发出此请求时,我遇到了cors问题:
componentDidMount = () => {
console.log('app loading...');
axios.get('some/random/api').then((res) => {
console.log(res, 'res');
})
}
这是我的服务器端代码的一部分:
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)
})
我该如何在客户端获取这些数据?
谢谢
npm install --save cors
const cors = require('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'}) });
作为快速解决方案,您还可以安装此chrome扩展程序
但是,持久的解决方案是使用yarn add cors
并将其添加到express js中的根文件中。 正如@Artem Mirchenko所强调的
根据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 });
});
});
编辑:现在我看,我不确定这是您想要的。 可能只需要从您的客户处调用其他服务,并包含cors信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.