【问题标题】:I can not configure the proxy in the create-react-app我无法在 create-react-app 中配置代理
【发布时间】:2019-06-10 07:29:59
【问题描述】:

我是 React 的初学者,我正在开发一个基于 React 文档的项目。

后端 api 服务器创建为 node.js 并由 PM2 作为 http://localhost:4005 管理。 前端使用 create-react-app 创建项目。

为了参考后端的api,我设置代理设置参考this manual

我尝试了 package.json 代理配置和使用 http-proxy-middleware 手动配置,但都不起作用。

代理配置好了,但是webpack dev-server调用自己如下图。

纱线启动消息(反应)

You can now view client in the browser.

  Local:            http://localhost:63323/
  On Your Network:  http://172.30.1.13:63323/

Note that the development build is not optimized.
To create a production build, use yarn build.

[HPM] Error occurred while trying to proxy request /api/getList from localhost:63323 to http://localhost:4005/ (ETIMEDOUT) (https://nodejs.org/api/errors.html#errors_common_system_errors)

浏览器控制台消息:

List.js:19 GET http://localhost:63323/api/getList 
net::ERR_CONNECTION_REFUSED
list:1 Uncaught (in promise) TypeError: Failed to fetch

(63323端口是react指定的端口)

我的项目目录如下所示:

Express 服务器 index.js

const express = require('express');
const path = require('path');

const app = express();

// Serve the static files from the React app
app.use(express.static(path.join(__dirname, 'client/build')));

// An api endpoint that returns a short list of items
app.get('/api/getList', (req,res) => {
    var list = ["item1", "item2", "item3"];
    console.log('Sent list of items:',list);
    res.json(list);
});


// Handles any requests that don't match the ones above
app.get('*', (req,res) =>{
    console.log('node -> react index.html');
    res.sendFile(path.join(__dirname+'/client/build/index.html'));
});

const port = process.env.PORT || 4005;
app.listen(port);

console.log('App is listening on port ' + port);

反应视图 list.js

import React, { Component } from 'react';

class List extends Component {
    // Initialize the state
    constructor(props){
        super(props);
        this.state = {
            list: []
        }
    }

    // Fetch the list on first mount
    componentDidMount() {
        this.getList();
    }

    // Retrieves the list of items from the Express app
    getList = () => {
        fetch('/api/getList')
            .then(res => {
                console.log('res!');
                res.json();
            })
            .then(list => {
                console.log('fetch list : ', list);
                this.setState({ list });
            })
    }

    render() {
        const { list } = this.state;

        return (
            <div className="App">
                <h1>List of Items</h1>
                {/* Check to see if any items are found*/}
                {list.length ? (
                    <div>
                        {/* Render the list of items */}
                        {list.map((item) => {
                            return(
                                <div>
                                    {item}
                                </div>
                            );
                        })}
                    </div>
                ) : (
                    <div>
                        <h2>No List Items Found</h2>
                    </div>
                )
                }
            </div>
        );
    }
}

export default List;

package.json

{
  "name": "client",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "http-proxy-middleware": "^0.19.1",
    "react": "^16.7.0",
    "react-dom": "^16.7.0",
    "react-router-dom": "^4.3.1",
    "react-scripts": "2.1.3"
  },
  "scripts": {
    "start": "PORT=4001 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"
  ],
  "proxy": "http://localhost:4005"
}

这与我称为 example 的帖子没有什么不同,但我想知道我错过了什么。

【问题讨论】:

  • 你试过直接在浏览器中访问localhost:63323/api/getList吗?
  • 因为我是初学者,所以我错过了很多东西。我知道控制台应该有一个代理地址,但@AshokGujjar 回复了它。非常感谢。

标签: javascript reactjs webpack proxy create-react-app


【解决方案1】:

我觉得你需要回res.json()

    fetch('/api/getList')
        .then(res => {
            console.log('res!');
            return res.json(); // Must be returned
        })
        .then(list => {
            console.log('fetch list : ', list);
            this.setState({ list });
        })

【讨论】:

  • 感谢您的回复。这是我的错。解决方法是将 127.0.0.1 client.dev 放在 /etc/hosts 中。发生端口冲突时,似乎是通过创建localhost以外的主机来创建新端口。
  • 啊,我明白了。嗯,这就是我能做的。很高兴你找到了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-08-04
  • 2017-12-04
  • 2020-04-14
  • 1970-01-01
  • 1970-01-01
  • 2020-01-26
  • 1970-01-01
相关资源
最近更新 更多