Skip to content

Instantly share code, notes, and snippets.

@yzhong52
Created May 24, 2020 20:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yzhong52/6d07929d660bb7fa7c4df12fe1e0f519 to your computer and use it in GitHub Desktop.
Save yzhong52/6d07929d660bb7fa7c4df12fe1e0f519 to your computer and use it in GitHub Desktop.
index.ts
// This snippet is a lazy, temporary, inappropriate, not secure fix for error:
//
// "No 'Access-Control-Allow-Origin' header is present on the requested resource".
//
// It works as a proxy and add 'Access-Control-Allow-Origin: *' to the response header.
//
// 1) Init proejct and add dependencies:
//
// ```
// npm init
// tsc --init
// npm install typescript
// npm install express
// npm install @types/express
// ```
//
// 2) Add this file.
//
// 3) Build and start server:
//
// ```
// tsc && node proxy.js
// ```
//
// 4) In your frontend application, change the request to "http://localhost:8079/api/v1/books" instead
// of "http://exmple.com/api/v1/books".
import express from 'express';
import * as request from "request-promise";
const app = express();
const port = 8079;
const bookServiceApi = 'http://exmple.com/api/v1/books'
app.use((req, res, next) => {
// It is *DANGEROUS* to allowing all cross region access.
res.header('Access-Control-Allow-Origin', '*');
next()
})
app.get('/api/v1/books', (req, res) => {
request.get(bookServiceApi).then(experiments => res.send(experiments))
});
app.listen(port, () => console.log(`Listening on port ${port}!`));