Reputation: 21
I am trying to post data from a python script to a Next js server.
#python script
import requests
post_data = {'username':'bob', 'id' : 32}
# POST some form-encoded data:
post_response = requests.post(url='http://localhost:3000/foo', data=post_data)
I do get a request on a server, but I do not know how to retrieve the data in getInitalProps(). I have looked at the documentation but there seems to be no such information.
static async getInitialProps({props, req})
{
console.log('request data: ', req.data);
}
Upvotes: 2
Views: 1524
Reputation: 7813
Crashed into the very same problem and found the solution well hidden in the Next.JS forums.
In short, first you need the Urlencoded Body Parser library to help parse the HTTP request object. Using npm
to install it:
npm install --save urlencoded-body-parser
Then in your code file, you call its function to get an object with the post variables in it:
import parse from 'urlencoded-body-parser';
static async getInitialProps(context)
{
if (context.req.method === "POST") {
const data = await parse(context.req);
console.log("request data: ", data);
}
}
Results, based on question sample data:
{
"username": "bob",
"id" : "32"
}
Upvotes: 3
Reputation: 8228
It should be like this:
static getInitialProps ({ query: { data } }) {
console.log('request data: ', data);
}
please not that you also need to pass the data in server.js:
server.get('/foo', (req, res) => {
return app.render(req, res, '/pageFoo', req.query)
})
Upvotes: 1