当前位置 : 主页 > 网页制作 > React >

reactjs – 使用react / axios清空POST请求

来源:互联网 收集:自由互联 发布时间:2021-06-15
我是node.js的新手并做出反应.我已经构建了一个后端api来为一个Products模型公开CRUD端点,它有三个字段:Title,Description和Price.我已经将node / express用于带有SQLite db文件的服务器. 我已经使用
我是node.js的新手并做出反应.我已经构建了一个后端api来为一个Products模型公开CRUD端点,它有三个字段:Title,Description和Price.我已经将node / express用于带有SQLite db文件的服务器.

我已经使用postman测试了端点,并且可以成功访问所有产品,检索单个产品,添加新产品(但仅将标头设置为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请求是空的.我很欣赏有关我做错的任何指示.

您可能正在使用不正确的内容类型.适当的内容类型应该是application / json.

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

网友评论