Home >Web Front-end >JS Tutorial >Detailed explanation of the steps to use express+http-proxy-middleware across domains

Detailed explanation of the steps to use express+http-proxy-middleware across domains

php中世界最好的语言
php中世界最好的语言Original
2018-06-01 09:47:533214browse

This time I will bring you a detailed explanation of the steps for using express http-proxy-middleware across domains on node. What are the precautions for using express http-proxy-middleware on node across domains? The following is a practical case. Get up and take a look.

Why use node proxy forwarding?

We want to separate the front-end and back-end, and then the front-end does not install tomcat on its own computer. At this time, we build a server with node and then forward our request. For example: our local host is localhost:3000, and we need to visit http://www.example.com (of course, during the development process, this should be the address of your backend tomcat) to do ajax data interaction.

Create project

npm init
Install module

npm install express connect-timeout http-proxy-middleware --save-dev
Create js file

<!--proxy-server.js-->
const express = require('express');
const timeout = require('connect-timeout');
const proxy = require('http-proxy-middleware');
const app = express();
// 超时时间
const TIME_OUT = 30 * 1e3;
// 设置端口
app.set('port', '80');
// 设置超时 返回超时响应
app.use(timeout(TIME_OUT));
app.use((req, res, next) => {
 if (!req.timedout) next();
});
proxyOption = {
 target: 'http://localhost:8080',
 pathRewrite: {
    '^/api/' : '/' // 重写请求,api/解析为/
  },
  changeOrigoin:true
};
// 静态资源路径
app.use('/', express.static('src/page'));
// 反向代理
app.use('/api/*', proxy(proxyOption));
// 监听端口
app.listen(app.get('port'), () => {
 console.log(`server running @${app.get('port')}`);
});
I believe you have mastered the method after reading the case in this article , for more exciting content, please pay attention to other related articles on the php Chinese website!

Recommended reading:

How to develop the verification code password input box function in the WeChat applet

How to use webpack3. 0Configure webpack-dev-server

The above is the detailed content of Detailed explanation of the steps to use express+http-proxy-middleware across domains. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn