【问题标题】:Problems with proxy server in react app with node.js express使用 node.js express 反应应用程序中的代理服务器问题
【发布时间】:2021-11-10 05:20:35
【问题描述】:

我在 server.js 中有简单的快速服务器

const express = require('express'); 
const app = express(); 
const port = process.env.PORT || 5000; 


app.listen(port, () => console.log(`Listening on port ${port}`)); 


app.get('/express_backend', (req, res) => { 
  res.send({ "express":"have data"}); 
}); 

也是组件

import { Component } from "react";
import './../css/Rings.css'
import SellItem from "./sellItem";
import Fotter from "./fotter";

    class Necklase extends Component{
        state ={
            data: null
        };
        componentDidMount() {
            this.callBackendAPI()
              .then(res => this.setState({ data: res.express }))
              .catch(err => console.log(err));
          }
        callBackendAPI = async () => {
            const response = await fetch('/express_backend');
            const body = await response.json();
            console.log(body.express)
            if (response.status !== 200) {
              throw Error(body.message) 
            }
            return body;
          };
        render(){
    
    
    
            return   <div >
            <div className="main">
                <SellItem/>
    
            </div>
            {this.state.data}
            <Fotter/>
        </div>
        }
    }
    export default Necklase

当我在包 json 中使用 npm start 启动我的 react 应用程序时,npm start 现在看起来像这样,也是代理

"start": "react-scripts start",
"proxy": "http://localhost:5000",

之后我在 cmd 中使用 node server.js 启动 server.js 一切正常,我可以从响应中获取数据并显示它,但是如果我将“start”更改为这个

"start": "react-scripts start && nodemon server.js  ",

我在控制台中收到此错误

Proxy error: Could not proxy request /express_backend from localhost:3000 to http://localhost:5000/.
See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (ECONNREFUSED).

当我在 callBackendAPI 中使用 console.log(body.express) 时

SyntaxError: JSON 中位置 0 的意外标记 P

【问题讨论】:

    标签: node.js reactjs express


    【解决方案1】:

    你可以试试这个方法

    "scripts": {
        "start": "nodemon --exec babel-node ./app.js",
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-26
      • 2020-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-14
      • 2017-03-21
      相关资源
      最近更新 更多