Skip to content

Instantly share code, notes, and snippets.

@yzhong52

yzhong52/index.ts

Created May 24, 2020
Embed
What would you like to do?
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}!`));
You can’t perform that action at this time.