background:
2018-04-11 wrote
Since the front end is loading images or other file resources that are not of this domain name, cross-domain problems will be reported. Based on this problem, I think of the nodejs koa framework as a static resource forwarding function.
The cross-domain error is as follows:
1597:1 Access to Image at 'https://xxx.com/static/image/[email protected]?' from origin 'https://xxx.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://xxx.com' is therefore not allowed access.
Actual combat:
According to the necessary dependencies: mainly the request module:
$ npm i -D koa koa-router request
Then let's make a forwarding server:
/** * Created by happy on 4/10/18. */ var Koa = require ('koa'); var Router = require('koa-router'); var request = require('request'); var app = new Koa (); var router = new Router(); var port = 7788; router.get('/', (ctx, next) => { ctx.body = 'hello'; }); // Here is the pleasure of doing static resource forwarding router.get('/static', (ctx, next) => { ctx.body = request.get(ctx.url.replace('/image?', '')); }); app .use(router.routes()) .use(router.allowedMethods()) .listen(port, () => console.log(`✅ The server is running at http://localhost:${port}`)); // Access: localhost:7788/static?xxx cross-domain server resources
Summarize:
Originally, I was going to use fetch to get the file stream, but I saw that all API attempts on the official website were reported as failures, so I used request to get the file stream.