Nathalie
Nathalie

Reputation: 41

empty POST request with react/axios

I'm new to node.js and react. I've built a back end api to expose CRUD endpoints for a Products model with three fields: Title, Description and Price. I've used node/express for the server with an SQLite db file.

I've tested the endpoints using postman and can successfully access all the products, retrieve a single product, add a new product (but only with the header set to application/x-www-form-urlencoded), and delete a product.

I'm loosely following a tutorial building the front end with react and using axios to make http requests. I can read without issue so get all and get one by ID is working.

However, I've hit a wall with my post request. If I send a post request I get this error backend in the api server console -

Unhandled rejection SequelizeValidationError: notNull Violation: product

And on the front end after about a couple of minutes from sending the request I get:

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)

If I remove the validation a new product is successfully added to the database, but all the values are null.

This is my ProductNew.js file:

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;

I found this issue on github which I hoped would have solved my problem. I've added various console.log to follow what is happening with the state data through the script but I can't see why my POST request is empty. I'd appreciate any pointers as to what I'm doing wrong.

Upvotes: 4

Views: 14624

Answers (2)

aslantorret
aslantorret

Reputation: 303

It appears that you may be using an incorrect Content type. The proper content type should be application/json.

The following answer has an example of the differing formats that are passed by the various content types, which may be contributing to your issues: differences in application/json and application/x-www-form-urlencoded

Upvotes: 1

Jakub Jurkian
Jakub Jurkian

Reputation: 1506

Maybe it will help you somehow. I think you have a problem with your axios request structure.

Docs say: axios.post(url[, data[, config]])

Instead of putting headers directly, as the last parameter:

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

you should have a config object that contains headers and then pass it as the last parameter:

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

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

Upvotes: 2

Related Questions