Created
May 24, 2020 20:15
-
-
Save yzhong52/6d07929d660bb7fa7c4df12fe1e0f519 to your computer and use it in GitHub Desktop.
index.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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}!`)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
References: