js启动一个简单服务指定启动目录和index.html,并配置接口代理
环境准备
node任意版本。
node包:express、http-proxy-middleware、http。
提前下载好包:
npm install express --save npm install http-proxy-middleware --save npm install http --save
目录结构
主要代码在server.js中,index.html为测试用的项目启动页,与server.js无关。
主要代码(server.js)
const express = require('express'); const app = express(); const http = require('http').createServer(app); const port = 8777; // 端口,自定义 const { createProxyMiddleware } = require('http-proxy-middleware'); // 创建代理中间件 const proxy = createProxyMiddleware({ target: 'http://192.168.3.114:8009', // 目标地址 changeOrigin: true, // 开启代理后是否改变请求头中的 Host 字段 pathRewrite: { '^/api/': '/', // 将所有以 /api/ 开头的请求路径重写为 / 开头的请求路径 }, }); // 在应用中使用代理中间件 app.use('/api', proxy); // 指定index.html文件作为默认路由 app.get('/', function(req, res) { res.sendFile(__dirname + '/index.html'); // __dirname为node自带的当前目录,可更改为目标目录 }); // 启动本地服务并监听指定端口 http.listen(port, function() { console.log(`Server started on port ${port}`); });
在index.html中用xhr直接调用(以某个post请求为例):
// 创建XMLHttpRequest对象 var xhr = new XMLHttpRequest(); // 设置请求方法和URL(这里尤其注意需要添加匹配字符串,上面server.js中配置的是/api,不然不会识别) xhr.open("POST", "/api/test"); // 设置请求头部信息 // xhr.setRequestHeader('Content-Type', 'application/json'); // 发送请求 xhr.send(JSON.stringify(data)); // 添加回调函数处理响应数据 xhr.onload = function() { if (xhr.status === 200) { // 请求成功,处理响应数据 console.log(data); } else { // 请求失败,处理错误信息 console.error("请求失败:" + xhr.statusText); } };