从React发送req.body到Express,然后发布到api

时间:2019-10-03 15:50:29

标签: reactjs api express post axios

我正在尝试将表单主体从React发送到Express,然后将其发布到API。一切似乎都可以正常工作,从而使主体从React到Express,但是我不确定如何将其发布到API。 GET请求从API正常工作,它只是将数据发送到POST而又遇到问题。我还使用了AXIOS。任何建议或教程的链接表示赞赏。

SiteAdd.js-从状态获取表单数据并从Express服务器获取路由。

       handleSubmit = e => {
    e.preventDefault();
    //deconstruct
    const { id, siteRef, addrType, addr1, addr2, city, county, postCode, country } = this.state;
    const site = {
      id,
      siteRef,
      addrType,
      addr1,
      addr2,
      city,
      county,
      postCode,
      country
    };

   fetch('/api/siteAdd', site)
      .then(() => console.log('Site Created'))
      .catch(err => {
        console.error(err);
      });
  };

server.js-Express服务器

       var express = require('express')
    var http = require('http')
    //var bodyParser = require('body-parser')
    var cors = require('cors')
    const path = require('path')
    var app = express()
    var axios = require('axios')

    app.use(express.urlencoded({ extended: false }));
    app.use(express.json());
    app.use(cors())

    //get
    //working
    app.get('/api/site', (req, res, next) => {
        axios.get('https://****/api/site/')
        .then(response => res.json(response.data))
            .catch(err => next(err));
    })

let sites = [];
app.post('/api/siteAdd', function (req, res) {
    const newSite = {
        id: req.body.id,
        siteRef: req.body.siteRef,
        addrType: req.body.addrType,
        addr1: req.body.addr1,
        addr2: req.body.addr2,
        city: req.body.city,
        county: req.body.county,
        postCode: req.body.postCode,
        country: req.body.country,
    };

    sites.push(newSite);
    console.log(sites);
});

1 个答案:

答案 0 :(得分:0)

尝试检查后端的错误日志,该日志返回状态代码500。您尝试发布数据的服务器上发生了问题。