I have a next js web app with express. I want to post data to this webpage fetch it on my server and pass it on to my next js page. I am new to next js and express. Following is my server.js code:-
const express = require('express')
const next = require('next')
const port = parseInt(process.env.PORT, 10) || 3000
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()
app.prepare().then(() => {
const server = express()
server.use(express.json());
server.post("/posts", (req, res) => {
req.body.data
console.log("Post data : ",req.body.data)
console.log("JSON Response : ",res.json());
});
// server.get('/posts/', (req, res) => {
// console.log("Post data again : ",res.body.data)
// return app.render(req, res, '/posts', { id: "Pritam" })
// })
server.get('*', (req, res) => {
return handle(req, res)
})
server.listen(port, err => {
if (err) throw err
console.log(`> Ready on http://localhost:${port}`)
})
})
When I use get request I am able to send data from my server to the client using return app.render(req, res, ‘/posts’, { name: “Pritam” }) but when I try to do the same thing with post I am not able to receive any data on my client. Initially, I have tried passing values in query params and it works fine. Following is my posts.js code:-
import React, { Component } from 'react'
class Posts extends Component {
static async getInitialProps ({ query: { id } }) {
console.log("Response is ")
return { postId: id }
}
render () {
return (
<div>
<p>Post data {this.props.postId}</p>
</div>
)
}
}
export default Posts;
I would like to create an endpoint from my server code to send data to my client and receive that data in getInitialProps and render it on my client-side. Any help or suggestion is much appreciated. Thank you.