server.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. const express = require('express');
  2. const request = require('request');
  3. const path = require('path');
  4. const bodyParser = require('body-parser');
  5. const app = express();
  6. const port = 5500;
  7. const requestHost = 'http://192.168.1.12:9001'
  8. app.use('/js', express.static(path.join(__dirname, 'js')));
  9. app.use('/css', express.static(path.join(__dirname, 'css')));
  10. app.use('/img', express.static(path.join(__dirname, 'img')));
  11. app.use('/index.html', express.static(path.join(__dirname, 'index.html')));
  12. app.use(bodyParser.json())
  13. // 允许跨域
  14. app.all('*', function (req, res, next) {
  15. res.header("Access-Control-Allow-Origin", '*');
  16. res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
  17. res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
  18. res.header("Access-Control-Allow-Credentials", "true");
  19. if (req.method === "OPTIONS") res.send(200);
  20. else next();
  21. });
  22. // 处理 GET 请求
  23. app.get('*', (req, res) => {
  24. const options = {
  25. url: requestHost + req.path,
  26. method: "GET",
  27. };
  28. request(options, function (error, response, body) {
  29. if (!error && response.statusCode === 200) {
  30. let headers = response.headers;
  31. res.setHeader('content-type', headers['content-type']);
  32. res.send(body);
  33. } else {
  34. res.send(options);
  35. }
  36. });
  37. });
  38. // 处理 POST 请求
  39. app.post('*', (req, res) => {
  40. const options = {
  41. url: requestHost + req.path,
  42. method: 'POST',
  43. json: req.body,
  44. headers: {
  45. 'content-type': req.headers['content-type']
  46. }
  47. };
  48. request(options, function (error, response, body) {
  49. if (!error) {
  50. let headers = response.headers;
  51. res.setHeader('content-type', headers['content-type']);
  52. res.send(body);
  53. } else {
  54. res.send(options);
  55. }
  56. });
  57. });
  58. app.listen(port, () => {
  59. console.log(`Example app listening at http://localhost:${port}`);
  60. });