代码之家  ›  专栏  ›  技术社区  ›  kshitij

React app未命中proxy()中描述的url包.json文件)

  •  0
  • kshitij  · 技术社区  · 7 年前

    "proxy": "http://localhost:3001" 在我的包.json express服务器在这个端口(3001)上运行,但每次我接到react的请求时,它都在运行react应用程序的3000端口上运行

    包.json

    {
      "name": "client",
      "version": "0.1.0",
      "private": true,
      "dependencies": {
        "antd": "^3.10.2",
        "axios": "^0.18.0",
        "dotenv": "^6.1.0",
        "http-proxy-middleware": "^0.19.0",
        "material-ui": "^0.20.2",
        "react": "^16.5.2",
        "react-bootstrap": "^0.32.4",
        "react-dom": "^16.5.2",
        "react-form": "^3.5.6",
        "react-redux": "^5.0.4",
        "react-router-dom": "^4.3.1",
        "react-router-redux": "^5.0.0-alpha.5",
        "react-scripts": "2.0.5",
        "styled-components": "^4.0.2"
      },
      "scripts": {
        "start": "react-scripts start",
        "build": "react-scripts build",
        "test": "react-scripts test",
        "eject": "react-scripts eject"
      },
      "eslintConfig": {
        "extends": "react-app"
      },
      "browserslist": [
        ">0.2%",
        "not dead",
        "not ie <= 11",
        "not op_mini all"
      ]
    }
    

    const proxy = require('http-proxy-middleware');
    
    module.exports = function(app) {
      app.use(proxy('/api/*', { target: 'http://localhost:3001' }));
    };
    
    2 回复  |  直到 7 年前
        1
  •  0
  •   williamZzzz    7 年前
    "proxy": {
    "/services": {
      "target": "http://localhost:3001",
      "changeOrigin": true,
      "pathRewrite": {
        "^/services": ""
      }
    }
    

    }

    npm重新开始

        2
  •  0
  •   User123456    7 年前

    您可以在索引.js

    const PORT = 3001;
    

    和使用

    "proxy": { "/*": { "target": "http://localhost:3001" } }
    

    在客户端包.json

    对于http代理中间件: 安装程序包。 创建一个名为设置代理.js

    const proxy = require('http-proxy-middleware');
    
    module.exports = function(app) {
      app.use(proxy('/', { target: 'http://localhost:3001' }));
    };
    

    记住从客户端删除旧的代理脚本代码包.json.

        3
  •  0
  •   Konstantin Grech    6 年前

    const { createProxyMiddleware } = require('http-proxy-middleware');
    
    module.exports = function(app) {
      app.use('/console/api', createProxyMiddleware({ 
        target: 'http://localhost:8080/', 
        changeOrigin: true, 
        pathRewrite: {'^/console/api' : ''} 
      }));
    };
    

    换句话说, proxy 应替换为 createProxyMiddleware

    推荐文章