NextJS: Form data isn't sent to the express server

Viewed 8103

I'm trying to send form data to server in a Nextjs/express app.When I press 'submit',I can't see any output is sent to server.

I tried the following code and had no success and I can't understand why it is not working because I'm totally a newbie to this stack.File structure of my project is as follows.

enter image description here

index.js

class Index extends Component{

render(){
return(
    <form action="/server" method="post">
        <input type="text" id="name"></input>
        <input type="submit"/>
    </form>
);
}
}

server.js

server.post('/server', (req, res) => {
    const name  = req.body
    res.send(name)
})

I want the webpage show the data that I entered into input field in the form.instead,it shows only a couple of curly braces( {} ).

1 Answers

EDIT

I toggled some stuff from your example repo on the front and backend. You can see them in the code examples!

In order to do this you need 2 things:

An onChange handler to handle the input and an onSubmit handler to handle the submission to the server. Here is my implementation of your example.

class Index extends Component {
    constructor() {
    super();
    this.state = {
        firstName: '',
    };
}
handleChange = evt => {
// This triggers everytime the input is changed
    this.setState({
        [evt.target.name]: evt.target.value,
    });
};
 handleSubmit = evt => {
      evt.preventDefault();
      //making a post request with the fetch API
      fetch('/server', {
        method: 'POST',
        headers: {
              'Accept': 'application/json',
              'Content-Type': 'application/json'
        }, 
        body: JSON.stringify({
             firstName:this.state.firstName
           })
        })
        .then(response => response.json())
        .then(data => console.log(data))
        .catch(error => console.log(error))
     });
  };
render(){
  return(
    <form onSubmit={this.handleSubmit} >
        <input 
            name="firstName" 
            type="text" 
            id="name" 
            value={this.state.firstName} 
            onChange={this.handleChange}>
        </input>
        <input type="submit"/>
    </form>
    );
  }
}

Your server code:

const express = require('express')
const next = require('next')
const bodyParser = require('body-parser')

const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()

app.prepare().then(() => {
  const server = express()
  server.use(bodyParser.urlencoded({ extended: true }))
  server.use(bodyParser.json())

  server.post('/server', (req, res) => {
    console.log(req.body)
    const firstName = req.body.firstName
    res.send({firstName})
})

  server.get('*', (req, res) => {
    return handle(req, res)
  })

  server.listen(3000, (err) => {
    if (err) throw err
    console.log('> Read on http://localhost:3000')
  })
})

Hope this helps!

Related