简体   繁体   English

使用Express JS进行API外部CALL(避免cors问题)

[英]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!我正在尝试使用 express js 进行 API 调用以获取一些数据,然后将它们用于我的学校项目! 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.所以我正在尝试使用 Express JS 创建我自己的代理。 Do I need to write something else on I app.get( '/' ) or is it okay with a slash.我是否需要在 app.get( '/' ) 上写其他东西,或者用斜杠可以吗? 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}`));```


Use the cors package like this像这样使用cors

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

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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