Home > Software design >  Keep getting error with simple ReactJS FORM posting to Express JS server
Keep getting error with simple ReactJS FORM posting to Express JS server

Time:11-17

I am new to ReactJS and trying to find a way to connect my React front end to my Express js backend. To do this, I am just setting up a simple form that sends a POST request after I press a register button in a form.

The problem is I keep getting these error messages in the console. These are the errors

POST http://localhost:3000/api/users 404 (Not Found)
Error: Request failed with status code 404
at createError (createError.js:16)
    at settle (settle.js:17)
    at XMLHttpRequest.onloadend (xhr.js:66)

This is the react code


import Proj from './Proj'
import React, {Fragment, useState} from 'react'
import axios from 'axios';


export const Homepage = () => {

    const [formData, setFormData] = useState({

        name:'',
     
        });

        const { name } = formData;

        const onChange = e =>
        setFormData({...formData, [e.target.name]:e.target.value})

    const onSubmit = async e => {
        console.log('submitted')
        e.preventDefault();
        const newUser = {
            name,
           
            }
            try {
                const config = {
                    headers:{
                        'Content-Type':'application/json'
                         } }
             const body = JSON.stringify(newUser)
             const res = await axios.post('/api/users',body, config)             
                console.log(res)
            } catch (err) {
                console.error(err)
            }
    }



    return (
        <div className="Landing">
                    <Proj/>
<section>
<form  onSubmit = {e=>onSubmit(e)}>
<input 
          type="text" 
          placeholder="Name" 
          name="name"
          value = {name}
          onChange = {e =>onChange(e)}
           required />   
<input type="submit" className="btn btn-primary" value="Register" />
<h1>Contact</h1>
    
</form>




</section>



        </div>
    )
}
export default Homepage

This App.js

import { Navbar } from './components/Navbar';
import Homepage from './components/Homepage';
import Projects from './components/Projects';
import {BrowserRouter as Router, Route, Switch} from 'react-router-dom';
import './App.css';

function App() {
  return (

    <Router>
    <div className="App">
      <Navbar/>
 
    </div>
    <Route exact path="/" component={Homepage} />
    <Switch>
    <Route exact path="/Projects" component={Projects} />
        </Switch>
    </Router>
  );
}

export default App;

This is my server side JS

const express = require ('express')
const path = require('path');

const app = express()

app.use(express.urlencoded({extended: false})); 


app.use('/', require('./routes/api/users'))

// Serve static assets in production
if (process.env.NODE_ENV === 'production'){

    app.use(express.static('client/build'))
    app.get('*', (req,res)=>{
    res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'))
    
    })
}



const PORT = 5000

app.listen(process.env.PORT || 5000)

and this is users.js in the api folder in routes

const express = require('express')
const router = express.Router();



router.post('/', async (req,res)=>
{

console.log('its  working, and here is the data', req.body)


})



module.exports = router;

client side package.json

"proxy":"http://localhost:5000",

I would really appreciate it if someone can tell me what I am doing wrong or if there is a better way to do things.Thanks.

CodePudding user response:

Instead of

app.use('/', require('./routes/api/users'))

type in

app.use('/api/users', require('./routes/api/users'))

You are posting currently to a route that does not exist.

  • Related