reactjs - 带有react/axios的空POST请求

标签 reactjs post axios

我是 Node.js 和 React 的新手。我构建了一个后端 API 来公开具有三个字段的 Products 模型的 CRUD 端点:TitleDescription价格。我使用 node/express 作为带有 SQLite 数据库文件的服务器。

我已经使用 postman 测试了端点,并且可以成功访问所有产品、检索单个产品、添加新产品(但仅限将 header 设置为 application/x-www-form-urlencoded),然后删除产品。

我正在大致遵循使用 react 构建前端并使用 axios 发出 http 请求的教程。我可以毫无问题地阅读,因此获取所有内容并通过 ID 获取一本是可行的。

但是,我的发帖请求遇到了困难。如果我发送 post 请求,我会在 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;

我找到了这个issue在 github 上,我希望它能解决我的问题。我添加了各种 console.log 来通过脚本跟踪状态数据发生的情况,但我不明白为什么我的 POST 请求为空。如果有人指出我做错了什么,我将不胜感激。

最佳答案

也许它会对你有所帮助。我认为您的 axios 请求结构有问题。

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

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

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

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

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

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

关于reactjs - 带有react/axios的空POST请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48248859/

相关文章:

javascript - 使用 forEach 和 axios 进行异步/等待

javascript - TypeError : (0 , _axios.default) 在 *.test.js 文件中使用 jest.mock ('axios' 时不是函数

javascript - 在 Reactjs 中隐藏分页页码

javascript - 仅在使用 HOC 时查询组件中的元素类型错误

javascript - 如何在React Native中调用Alert onPress并传递一些参数

reactjs - 如何在 create-react-app 项目中为 lodash 执行 Tree Shaking?

swift - POST 请求未在 Swift 中发送

ios - 创建 iOS 客户端服务器应用程序。 ASIFormDataRequest 问题

Python 通过请求更改 Instagram 个人资料图片

reactjs - 为什么axios发送OPTIONS请求方法而不是DELETE或PUT方法