使用react / axios的空POST请求

时间:2018-01-14 10:56:36

标签: reactjs post axios

我是node.js的新手并做出反应。我已经为Products模型构建了一个后端api来公开 CRUD端点,其中有三个字段:TitleDescriptionPrice 。我已经使用 node / express SQLite db文件服务器。

我使用邮递员测试了端点,可以成功访问所有产品,检索单个产品,添加新产品(但只有标题设置为application/x-www-form-urlencoded),并删除产品。

我正在松散地按照教程构建前端做出反应并使用 axios 来发出http请求。我可以毫无问题地阅读,所以得到所有并通过ID得到一个正在工作。

然而,我的帖子请求已经碰壁了。如果我发送一个帖子请求,我会在api服务器控制台中收到此错误后端 -

Unhandled rejection SequelizeValidationError: notNull Violation: product

在发送请求大约几分钟后,在前端,我得到了:

XHR failed loading: POST "http://localhost:3000/api/products/new".
dispatchXhrRequest @ xhr.js:178
xhrAdapter @ xhr.js:12
dispatchRequest @ dispatchRequest.js:59
Promise resolved (async)
request @ Axios.js:51
Axios.(anonymous function) @ Axios.js:71
wrap @ bind.js:9
NewProduct._this.createHandler @ ProductNew.js:25
callCallback @ react-dom.development.js:542
invokeGuardedCallbackDev @ react-dom.development.js:581
invokeGuardedCallback @ react-dom.development.js:438
invokeGuardedCallbackAndCatchFirstError @ react-dom.development.js:452
executeDispatch @ react-dom.development.js:836
executeDispatchesInOrder @ react-dom.development.js:858
executeDispatchesAndRelease @ react-dom.development.js:956
executeDispatchesAndReleaseTopLevel @ react-dom.development.js:967
forEachAccumulated @ react-dom.development.js:935
processEventQueue @ react-dom.development.js:1112
runEventQueueInBatch @ react-dom.development.js:3607
handleTopLevel @ react-dom.development.js:3616
handleTopLevelImpl @ react-dom.development.js:3347
batchedUpdates @ react-dom.development.js:11082
batchedUpdates @ react-dom.development.js:2330
dispatchEvent @ react-dom.development.js:3421
09:59:59.293 ProductNew.js:30 

Error: Network Error
at createError (createError.js:16)
at XMLHttpRequest.handleError (xhr.js:87)

如果我删除了验证,则新产品已成功添加到数据库中,但所有值均为 null

这是我的ProductNew.js文件:

import React from 'react';
import axios from'axios';
import ButtonAdd from '../components/Buttons/ButtonAdd';

class NewProduct extends React.Component {
  state = {
    title: '',
    description: '',
    price: ''
  }
  createHandler = () => {
    const data = {
      Title: this.state.title,
      Description: this.state.description,
      Price: this.state.price
    };
    console.log('Raw data is: ' + Object.entries(data));
    // => Raw data is: Title,burger,Description,bun,Price,5

    const header = {
      ContentType: 'application/x-www-form-urlencoded',
      Accept: 'application/json'
    };
    const querystring = require('querystring');
    console.log(querystring.stringify(data));
    // => Title=burger&Description=bun&Price=5

    console.log('Data is:' + JSON.stringify(data));
    // => Data is:{"Title":"burger","Description":"bun","Price":"5"}

    axios.post('/api/products/new', querystring.stringify(data), header)
    .then(res => {
      console.log(res);
    })
    .catch(err => {
      console.log(err);
    });
  }

  render () {
    return (
      <div className='NewPost'>
        <h1>Add a Product</h1>
        <label>Title</label>
        <textarea rows='4' value={this.state.title} onChange={(event) => this.setState({title: event.target.value})} />
        <label>Description</label>
        <textarea rows='6' value={this.state.description} onChange={(event) => this.setState({description: event.target.value})} />
        <label>Price</label>
        <input type='number' value={this.state.price} onChange={(event) => this.setState({price: event.target.value})} />
        // ButtonAdd.js onClick={props.create} added to <Button> tag
        <ButtonAdd create={this.createHandler}>Add New Product</ButtonAdd>
      </div>
    );
  }
}

export default NewProduct;

我在github上找到了这个issue,我希望能解决我的问题。我已经添加了各种console.log来跟踪状态数据通过脚本发生的事情,但我不明白我的POST请求为空的原因。我很欣赏任何关于我做错事的指示。

2 个答案:

答案 0 :(得分:1)

您可能使用的内容类型不正确。正确的内容类型应为application/json

以下答案中包含各种内容类型传递的不同格式的示例,这些格式可能会导致您的问题:differences in application/json and application/x-www-form-urlencoded

答案 1 :(得分:0)

也许它会以某种方式帮助你。我认为您的axios请求结构存在问题。

文档说:axios.post(url[, data[, config]])

而不是直接放置标题,作为最后一个参数:

axios.post('/api/products/new', querystring.stringify(data), header)

你应该有一个包含标题的配置对象,然后将其作为最后一个参数传递:

const config = {
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    'Accept': 'application/json'
  }
};

axios.post('/api/products/new', querystring.stringify(data), config)