React 代理,服务器响应状态为 404(未找到)

问题描述 投票:0回答:2

默认情况下,我在 localhost: 3000 上运行。 我想使用代理设置向 localhost:8072 发送请求。 我已完成代理设置,但收到错误。

另外终端显示错误

npm 错误! 类型:'系统', npm 错误! errno: 'ECONNREFUSED', npm 错误! 代码:'ECONNREFUSED', npm 错误! 父级:“流程管理器” npm 错误! npm 错误!如果您使用代理,请确保 npm 错误! “代理”配置设置正确。 请参阅:“npm 帮助配置” FetchError:请求 http://localhost:8072/ 失败,原因:连接 ECONNREFUSED 127.0.0.1:8072

我把我的代码放在下面。

此外,我在终端中看到这样的错误。

package.json

`

{
  "name": "process-manager",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.11.6",
    "@testing-library/react": "^11.2.2",
    "@testing-library/user-event": "^12.2.2",
    "axios": "^0.21.0",
    "http-proxy-middleware": "^1.0.6",
    "proxy": "http://localhost:8072",
    "react": "^17.0.1",
    "react-dom": "^17.0.1",
    "react-redux": "^7.2.2",
    "react-router-dom": "^5.2.0",
    "react-scripts": "^4.0.1",
    "web-vitals": "^0.2.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

`

src/setupProxy.js

`

const { createProxyMiddleware } = require('http-proxy-middleware');

module.exports = function (app) {
  app.use(
    '/api',
    createProxyMiddleware({
      target: 'http://localhost:8072',
      changeOrigin: true,
    })
  );
};

`

登录.js

`

import React, { useState } from 'react';
import querystring from 'querystring';
import axios from 'axios';
import classes from './LoginPage.module.css';
import { useHistory } from "react-router-dom";

const LoginPage = (props) => {
  const [emailState, setEmailState] = useState();
  const [passwordState, setPasswordState] = useState();
  const history = useHistory();

  const handleSubmit = async (e) => {
    e.preventDefault();

    try {
      const response = await axios.post(
        // 'http://localhost:8072/oauth/token',
        'api/oauth/token',
        querystring.stringify({
          username: emailState,
          password: passwordState,
          grant_type: 'password',
          provider: 'default'
        }),
        {
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Authorization': 'Basic ZGV2Z2xhbi1jbGllbnQ6ZGV2Z2xhbi1zZWNyZXQ='
          }
        }
      )
      console.log(response.data);
    } catch (error) {
      return alert(error);
    }

    history.push('/');
  };

  return (
    <div className={classes['login-page']} >
      <form onSubmit={handleSubmit}>
        <h1 className={classes['login-header']} >Login</h1>
        <div className="classes.block">
          <label>
            Email:
          </label>
          <input type="email"
            name="email"
            required
            className={classes['classes-inputs']}
            onChange={e => setEmailState(e.target.value)} />
        </div>
        <div className={classes.block}>
          <label>
            Password:
          </label>
          <input type="password"
            name="password"
            autoComplete="on"
            required
            className={classes['classes-inputs']}
            onChange={e => setPasswordState(e.target.value)} />
        </div>
        <div className={classes.block}>
          <input type="submit" value="Login" onSubmit={handleSubmit} />
        </div>
      </form>
    </div>
  )
}

export default LoginPage;

`

我哪里做错了?你能帮我吗?

reactjs proxy react-redux react-router axios
2个回答
2
投票

尝试改变

来自

const response = await axios.post(
        'api/oauth/token',

const response = await axios.post(
        '/api/oauth/token',

0
投票

希望这对某人有帮助。就我而言,我必须将路径重写包含为添加基本路径。这让我很困惑,但它解决了我的问题。另外,对于 TypeScript 用户,请确保该文件是

.js
而不是
.ts
作为代理中间件。

const { createProxyMiddleware } = require('http-proxy-middleware');

module.exports = function(app) {
  app.use(
    '/api',
    createProxyMiddleware({
      target: 'https://test-api.com',
      changeOrigin: true,
      /*This line fixed the issue*/
      pathRewrite: {
        "^/": "/api/" //add base path according to API route
      }
    })
  );
};
© www.soinside.com 2019 - 2024. All rights reserved.