React + Express:尝试使用fetch获取数据时出错ECONNREFUSED

时间:2018-04-26 00:36:28

标签: node.js reactjs express

返回节点,但我无法连接我的前端(React)和后端(Node / Express)。我在他的网站上浏览了David Ceddia的文章并且它有效,100%与他的例子一起工作。

当试图将同样的逻辑转移到我自己的应用程序中时,我正在

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

当然,我发现该部分标有ECONNREFUSED,并且说

ECONNREFUSED (Connection refused): No connection could be made because the target machine actively refused it. This usually results from trying to connect to a service that is inactive on the foreign host.

所以连接被拒绝,但我无法弄清楚原因。

BACKEND

users.js (我们要求提供信息的页面)

var express = require('express');
var router = express.Router();

/* GET users listing. */
router.get('/', function (req, res, next) {
  // Comment out this line:
  //res.send('respond with a resource');

  // And insert something like this instead:
  res.json([{
    id: 1,
    username: "samsepi0l"
  }, {
    id: 2,
    username: "D0loresH4ze"
  }]);
});

module.exports = router;

FRONT

的package.json

{
  "name": "shinyspork",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "react": "^16.3.2",
    "react-dom": "^16.3.2",
    "react-jss": "^8.4.0",
    "react-router-dom": "^4.2.2",
    "react-scripts": "1.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  },
  "proxy": "http://localhost/3001"
}

App.js

import React, { Component } from 'react';

class App extends Component {
  state = { users: [] }

  componentDidMount() {
    fetch('/users')
      .then(res => res.json())
      .then(users => this.setState({ users }));
  }

  render() {
    return (
      <div className="App">
        <h1>Users</h1>
        {this.state.users.map(user =>
          <div key={user.id}>{user.username}</div>
        )}
      </div>
    );
  }
}

export default App;

0 个答案:

没有答案