1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768 |
- const express = require('express');
- const request = require('request');
- const path = require('path');
- const bodyParser = require('body-parser');
- const app = express();
- const port = 5500;
- const requestHost = 'http://192.168.1.12:9001'
- app.use('/js', express.static(path.join(__dirname, 'js')));
- app.use('/css', express.static(path.join(__dirname, 'css')));
- app.use('/img', express.static(path.join(__dirname, 'img')));
- app.use('/index.html', express.static(path.join(__dirname, 'index.html')));
- app.use(bodyParser.json())
- // 允许跨域
- app.all('*', function (req, res, next) {
- res.header("Access-Control-Allow-Origin", '*');
- res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
- res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
- res.header("Access-Control-Allow-Credentials", "true");
- if (req.method === "OPTIONS") res.send(200);
- else next();
- });
- // 处理 GET 请求
- app.get('*', (req, res) => {
- const options = {
- url: requestHost + req.path,
- method: "GET",
- };
- request(options, function (error, response, body) {
- if (!error && response.statusCode === 200) {
- let headers = response.headers;
- res.setHeader('content-type', headers['content-type']);
- res.send(body);
- } else {
- res.send(options);
- }
- });
- });
- // 处理 POST 请求
- app.post('*', (req, res) => {
- const options = {
- url: requestHost + req.path,
- method: 'POST',
- json: req.body,
- headers: {
- 'content-type': req.headers['content-type']
- }
- };
- request(options, function (error, response, body) {
- if (!error) {
- let headers = response.headers;
- res.setHeader('content-type', headers['content-type']);
- res.send(body);
- } else {
- res.send(options);
- }
- });
- });
- app.listen(port, () => {
- console.log(`Example app listening at http://localhost:${port}`);
- });
|