获取API不通过发布发送数据

时间:2019-01-19 18:23:12

标签: javascript node.js reactjs express

我在使用Fetch API通过发布发送数据时遇到问题,服务器仅收到一个空JSON。有人能帮我吗?基本上,我正在更新状态下的数据并发送给API。

submitedData =请求。

submitedData = async (event) => {
   event.preventDefault();
   let data = {produto: this.state.produto, preco: this.state.preco};
   data = JSON.stringify(data);
   const result = await fetch('/api/add', {
       method: 'post',
       body: data
   });
   const body = await result.json();
   if(result.status == 200){
       //if all that's ok
   }else{
       console.log(body.message);
   }
}

changeInput =更改状态。

changeInput = (event) => {
    const field = event.target.name;
    this.setState({ [field]: event.target.value });
}

render =触发SubmittedData。

render(){
    return(
        <Grid>
            <Row>
                <Col sm={12}>
                    <Form horizontal onSubmit={this.submitedData} >
                        <FormGroup>
                            <Col sm={1}> <b> Produto: </b> </Col>
                            <Col sm={8}> 
                                <FormControl type="text" placeholder="Produto" value={this.state.produto} onChange={this.changeInput} name="produto" required/>
                            </Col>
                        </FormGroup>
                        <FormGroup>
                            <Col sm={1}> <b> Preço: </b> </Col>
                            <Col sm={8}> 
                                <FormControl type="number" placeholder="Preço" value={this.state.preco} onChange={this.changeInput} name="preco" required />
                            </Col>
                        </FormGroup>
                        <FormGroup>
                            <Col smOffset={1} sm={8}>
                                <Button type="submit" bsStyle="success"> Salvar </Button>
                            </Col>
                        </FormGroup>
                    </Form>
                </Col>
            </Row>
        </Grid>
    );
}

API

var express = require('express');
var Crud = require('./database/Crud');
var bodyParser = require('body-parser');
var app = express();

app.use(bodyParser.json());

app.post('/api/add', function(req, res){
  res.send(req.body);
  console.log(req.body); // {} json empty
});

1 个答案:

答案 0 :(得分:2)

您需要对请求主体进行字符串化并添加JSON内容类型标头。

const result = await fetch('/api/add', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify(data)
});