0

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}`));```


2
  • nothing wrong with doing it, though you might want to add cors package to handle it for you. and you can do res.pipe in place of most of your code.. fyi request package is deprecated Commented Mar 13, 2020 at 0:36
  • i am actually new to express js so i was thinking to make it work first like this and than add some middleware to my code! feel free to suggest your idea Commented Mar 13, 2020 at 0:38

1 Answer 1

3

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) => { 

});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.