简体   繁体   中英

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:

  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

  • Install cors library: npm install --save cors
  • Import it to your express project: const cors = require('cors');
  • Attach cors to your express app, before routes definitions: 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

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. as highlighted above by @Artem Mirchenko

you need to wrap your server code in a route, as per artem's answer likey so:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM