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);
}
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"
}
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) })
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.