Fazli Zekiqi
Fazli Zekiqi

Reputation: 571

Using Express JS to make API external CALL (avoiding cors problem)

I am trying to make API calls using express js to get some data and then use them for my school project! I have heard that I can install an extension or something like that on my browser but that will only work on my pc.

So I am trying to create my own proxy using Express JS. Do I need to write something else on I app.get('/') or is it okay with a slash. Thanks in advance!

const express = require('express');
const request = require('request');

const app = express();

app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  next();
});

let key1 = '8151a53b2c1d4c3db2df'
let url ='http://api.sl.se/api2/realtimedeparturesv4.json?key='+key1+'&siteid=9192&timewindow=5'


app.get('/', (req, res) => {
  request( { url: url},
    (error, response, body) => {
      if (error || response.statusCode !== 200) {
        return res.status(500).json({ type: 'error', message: err.message });
      }
      res.json(JSON.parse(body));
      console.log(body);
    } )
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`listening on ${PORT}`));```


Upvotes: 0

Views: 419

Answers (1)

mousto090
mousto090

Reputation: 2039

Use the cors package like this

var express = require('express')
var cors = require('cors')
var app = express()

app.use(cors())

if you want to enable it for a single route :

app.get('/', cors(), (req, res) => { 

});

Upvotes: 3

Related Questions