使用Fetch,Express.js和webpack在React.js中发出POST请求?

时间:2018-03-15 17:25:03

标签: javascript reactjs express fetch

我的React应用程序由port:8000:

上的webpack提供

令我感到困惑的是,在GET上快速服务器apiport 8016检索我的数据时,抓取是没有问题的。但是不能成为POST。我实际上得到了这个错误:

 From localhost:8000

 Error in sending data to server: Failed to fetch

那我怎么告诉它去8016

这是我的webpack.config.js处理我的服务器配置的部分,我正在运行我的快速服务器的代理:

devServer: {
    contentBase: path.join(__dirname, 'public'),
    clientLogLevel: 'warning',
    historyApiFallback: true,
    host: '0.0.0.0',
    hot: true,
    port: 8000, // <--- React/Frontend
    proxy: {
      '/api/*': 'http://localhost:8016', // <--- Express server
    },
  },

这是我的快递服务器:

var express = require('express');
var app = express();
var path = require('path');

var bodyParser = require('body-parser');

app.set('port', process.env.PORT || 8016);

var issues = [
  {
    id: 1,
    status: 'Open',
    owner: 'Ravan',
    created: new Date('2016-08-15'),
    effort: 5,
    completionDate: undefined,
  },
  {
    id: 2,
    status: 'Assigned',
    owner: 'Eddie',
    created: new Date('2016-08-16'),
    effort: 14,
    completionDate: new Date('2016-08-30'),
    title: 'Missing bottom border on panel',
  },
]; // global data

app.use(express.static(path.join(__dirname, '..', 'public')));
app.use(bodyParser.json());

app.get('/api/issues', (req, res) => {
  var metadata = { total_count: issues.length };
  res.json({ _metadata: metadata, records: issues });
});

app.post('/api/issues', (req, res) => {
  var newIssue = req.body;
  newIssue.id = issues.length + 1;
  newIssue.created = new Date();
  if (!newIssue.status) {
    newIssue.status = 'New';
    issues.push(newIssue);
    res.json(newIssue);
  }
});

// sends index.html
app.use('*', (req, res) => {
  res.sendFile(path.join(__dirname, '..', 'public/index.html'));
});

app.listen(app.get('port'), function(error) {
  console.log(`App started on port ${app.get('port')}!`);
});

以下是我的组件代码中的代码:

export default class IssueList extends Component {
  constructor() {
    super();
    this.state = { issues: [] }; // Component state initialized to an empty array

    this.createIssue = this.createIssue.bind(this); //binding the 'createIssue' function to always be called in Issuelist context
  }

  componentDidMount() {
    // upon component mounting kick off loadData();
    this.loadData();
  }

  loadData() {
    fetch('/api/issues')
      .then(response => response.json())
      .then(data => {
        console.log('Total count of records:', data._metadata.total_count);
        data.records.forEach(issue => {
          issue.created = new Date(issue.created);
          if (issue.completionDate) issue.completionDate = new Date(issue.completionDate);
        });
        this.setState({ issues: data.records });
      })
      .catch(err => {
        console.log(err);
      });
  }

  createIssue(newIssue) {
    fetch('/api/issues', {
      method: 'POST',
      body: JSON.stringify(newIssue),
      headers: new Headers({
        'Content-Type': 'application/json',
      }),
    })
      .then(response => response.json())
      .then(updatedIssue => {
        updatedIssue.created = new Date(updatedIssue.created);
        if (updatedIssue.completionDate) updatedIssue.completionDate = new Date(updatedIssue.completionDate);
        const newIssues = this.state.issues.concat(updatedIssue);
        this.setState({ issues: newIssues });
      })
      .catch(err => {
        alert('Error in sending data to server: ' + err.message);
      });
  }

  render() {
    return (
      <div>
        <h1>Issue Tracker</h1>
        <IssueFilter />
        <hr />
        <IssueTable issues={this.state.issues} /> {/* pass down this.state.issues to IssueTable */}
        <hr />
        <IssueAdd createIssue={this.createIssue} /> {/* pass down this.createIssue to IssueAdd */}
      </div>
    );
  }
}

提前致谢!

0 个答案:

没有答案