카테고리 없음

[Node.js] CORS and RESTAPI (Get API from URL)

brightlightkim 2022. 3. 20. 03:42

How to get API Data using function in Vue.js?

async getpolitics() {
      // `this` points to the vm instance
      console.log("politics");
      var url = "https://zlzlap7j50.execute-api.us-east-1.amazonaws.com/prod"
      try {
        let response = await axios.get(url);
        this.politics = response.data;
        console.log(this.politics);
        return true;
      }
      catch (error) {
        console.log(error);
      }
    },

This results in error

 

So it basically get the data using the url and store it.

and add a call to this function in the "created" function

  created: function() {
    this.getpokis();
    this.getpolitics();
  },

And add politics as an array in the data object

data: {
    pokis: [],
    politics:[],
    pokiName: '',
    pokiURL: '',
  },

You will get a CORS error on the console of your browser.

So, lets make a proxy for this route in routes/index.js

First add the request module to the top of your routes/index.js file

var request = require('request')

Then install the module

npm install request --save

Then use 'request' to pipe the output from the real URL back through the node server to your browser.

 

If this installing doesn't work because of the permission issue, do this command in the wsl of Ubuntu instead.

 

How to Use the request and pipe it to get around the CORS Error.

indes.js (Back End)

var politics = "https://zlzlap7j50.execute-api.us-east-1.amazonaws.com/prod";
router.get('/politics', function(req,res) {
  console.log("In politics");
  request(politics).pipe(res);
});

In App.js.. (Front End)

data: {
    politics:[],
  },
  created: function() {
    this.getpolitics();
  },
  methods: {    
    async getpolitics() {
      // `this` points to the vm instance
      console.log("politics");
      var url = "http://localhost:8080/politics";
      try {
        let response = await axios.get(url);
        this.politics = response.data;
        console.log(this.politics);
        return true;
      }
      catch (error) {
        console.log(error);
      }
    },

So it stores in our backend as a json first and then use the url in our axios to get around the CORS Error