Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to post data from react to express

I am trying to create a book app i have react on the front and node js on the backend. When i tried to create in backend its say Cannot POST /create.What do i have to do ,the folder is divided into front end and backend. i am using axios.I am new to react js please help.How can i pass data from a form in react to express to save.

this is the react component create

import React, {Component} from 'react';

class Create extends Component{
    render(){
        return(
            <div>
                <br/>
                <div class="container">
                    <form action="http://127.0.0.1:3000/create" method="post">
                        <div style={{width: '30%'}} class="form-group">
                            <input  type="text" class="form-control" name="BookID" placeholder="Book ID"/>
                        </div>
                        <br/>
                        <div style={{width: '30%'}} class="form-group">
                                <input  type="text" class="form-control" name="Title" placeholder="Book Title"/>
                        </div>
                        <br/>
                        <div style={{width: '30%'}} class="form-group">
                                <input  type="text" class="form-control" name="Author" placeholder="Book Author"/>
                        </div>
                        <br/>
                        <div style={{width: '30%'}}>
                            <button class="btn btn-success" type="submit">Create</button>
                        </div> 
                    </form>
                </div>
            </div>
        )
    }
}

export default Create;

this index.js in the backend

    var express = require('express');
    var app = express();
    var bodyParser = require('body-parser');
    var session = require('express-session');
    var cookieParser = require('cookie-parser');
    var cors = require('cors');
    app.set('view engine', 'ejs');

    //use cors to allow cross origin resource sharing
    app.use(cors({
        origin: 'http://localhost:3000',
        credentials: true
    }));




var books = [{
        "BookID": "1",
        "Title": "Book 1",
        "Author": "Author 1"
    },
    {
        "BookID": "2",
        "Title": "Book 2",
        "Author": "Author 2"
    },
    {
        "BookID": "3",
        "Title": "Book 3",
        "Author": "Author 3"
    }
]




app.get('/home', function (req, res) {
    console.log("Inside Home Login");
    res.writeHead(200, {
        'Content-Type': 'application/json'
    });
    console.log("Books : ", JSON.stringify(books));
    res.end(JSON.stringify(books));

})

app.post('/create', function (req, res) {
    var newBook = {
        "BookID": req.body.BookID,
        "Title": req.body.Title,
        "Author": req.body.Author
    }
    books.push(newBook)
    console.log(books);



})
//start your server on port 3001
app.listen(3001);
console.log("Server Listening on port 3001");
like image 482
e.T55 Avatar asked Mar 01 '19 21:03

e.T55


People also ask

How to create a blog with react Express Express?

Express Setup — To create a blog using React start by installing the express generator with this command: Run the express command in the Server directory. By this, you can get hands-on a default express application but do not utilize the default configuration as you need to modify it first.

How do I make a POST request with react and Python?

With our JSON data and Python server set up, we can focus on the React code and do a POST request using fetch (): When we run the React code, we get the following output in the browser: The output is simple — just a button rendered to the screen.

What is the difference between NodeJS Express and react?

– Node.js Express exports REST APIs & interacts with PostgreSQL Database using Sequelize ORM. – React Client sends HTTP Requests and retrieves HTTP Responses using Axios, consume data on the components. React Router is used for navigating to pages.

How to get started with ReactJS?

Any developer, who has good know-how about JS functions, can easily start using ReactJS. Developers will be able to define interfaces with JSX that are syntax like HTML. Due to this, the production of CSS & HTML occurs. React’s API is robust and anyone can simply get started by learning some basic functions.


1 Answers

There were a few errors. Here is some updated code and a description of what was going on:

React App.js:

import React, { Component } from 'react';
import axios from 'axios';

class Create extends Component {
  constructor(props) {
    super(props);

    this.state = {
      bookID: '',
      bookTitle: '',
      bookAuthor: '',
    };
  }

  handleInputChange = e => {
    this.setState({
      [e.target.name]: e.target.value,
    });
  };

  handleSubmit = e => {
    e.preventDefault();

    const { bookID, bookTitle, bookAuthor } = this.state;

    const book = {
      bookID,
      bookTitle,
      bookAuthor,
    };

    axios
      .post('http://localhost:3001/create', book)
      .then(() => console.log('Book Created'))
      .catch(err => {
        console.error(err);
      });
  };

  render() {
    return (
      <div>
        <br />
        <div className="container">
          <form onSubmit={this.handleSubmit}>
            <div style={{ width: '30%' }} className="form-group">
              <input
                type="text"
                className="form-control"
                name="bookID"
                placeholder="Book ID"
                onChange={this.handleInputChange}
              />
            </div>
            <br />
            <div style={{ width: '30%' }} className="form-group">
              <input
                type="text"
                className="form-control"
                name="bookTitle"
                placeholder="Book Title"
                onChange={this.handleInputChange}
              />
            </div>
            <br />
            <div style={{ width: '30%' }} className="form-group">
              <input
                type="text"
                className="form-control"
                name="bookAuthor"
                placeholder="Book Author"
                onChange={this.handleInputChange}
              />
            </div>
            <br />
            <div style={{ width: '30%' }}>
              <button className="btn btn-success" type="submit">
                Create
              </button>
            </div>
          </form>
        </div>
      </div>
    );
  }
}

export default Create;
  1. You were getting errors for using class and not className. class is a reserved word in react.js and should not be used.
  2. You were using the default post method which I would not recommend. I split the post out into it's own action and used the common library axios to make the CORS post call. I also created a function to handle the input changing on every key press with react.js.
  3. I added state to your component. This is common when there are form inputs to store them in state. I also changed the name of your variables to be title case which is the common way to write code variables.

Node.js index.js:

const express = require('express');
const logger = require('morgan');
const cors = require('cors');

const app = express();

//use cors to allow cross origin resource sharing
app.use(
  cors({
    origin: 'http://localhost:3000',
    credentials: true,
  })
);

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));

let books = [];

app.get('/home', function(req, res) {
  console.log('Inside Home Login');
  res.writeHead(200, {
    'Content-Type': 'application/json',
  });
  console.log('Books : ', JSON.stringify(books));
  res.end(JSON.stringify(books));
});

app.post('/create', function(req, res) {
  const newBook = {
    BookID: req.body.bookID,
    Title: req.body.bookTitle,
    Author: req.body.bookAuthor,
  };

  books.push(newBook);
  console.log(books);
});

//start your server on port 3001
app.listen(3001, () => {
  console.log('Server Listening on port 3001');
});

  1. You weren't parsing the body of the req, so it was coming back as undefined. I added app.use(express.json()); and app.use(express.urlencoded({ extended: false })); which should take care of most of the issues.
  2. I updated the req.body variables to match those coming over from React.
  3. I added the module morgen which you see here app.use(logger('dev')); this is helpful by showing all your requests and statuses for dev purposes. In this case, it was showing that you were getting a 500 (internal server error) because express couldn't read bookID of undefined (because the body wasn't being parsed).

This should be working now, let me know if you have any problems.

like image 194
Borduhh Avatar answered Oct 12 '22 06:10

Borduhh