1

I try to send data from my client to my server. For that, i use React with NextJS, because you have the server and client-side in one app.

I use the following handleSubmitFunction:

handleSubmit() {
  const email = this.state.email;
  fetch('/', {
    method: 'POST',
    body: email,
  });
}

and this is my server.js file in the located in / at my project

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()

  //parse application
  server.use(bodyParser.urlencoded({ extended: false}))

  //parse application/json
  server.use(bodyParser.json())

  server.post('/', (req, res) => {
    console.log(req.body.email);
    res.end("success!");
  })

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

  server.listen(3000, (err) => {
    if (err) throw err
    console.log('> Ready on http://localhost:3000')
  })
})
.catch((ex) => {
  console.error(ex.stack)
  process.exit(1)
})

When the handleSubmit Function is running, i get the following Output from the Server Console:

Cannot read property 'email' of undefined

Where exactly is my mistake? I have little experience in node JS environments. I would be very grateful if you could show me concrete solutions. Thank you for your replies.

1 Answer 1

2

It seems you have to parse header and JSON.stringify the email.

fetch('/', {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({email:email}),
    }).then((res)=> console.log('Worked'))
Sign up to request clarification or add additional context in comments.

1 Comment

i added another question: stackoverflow.com/questions/52559046/…? Could you look at the question?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.