I'm writing code in ironpython and I'm trying to send a http post request to the server with json in the request body. For this I use the C# method: HttpWebRequest
. I know there are more advanced and simpler methods, but this is the way I have to work.
My server is written in nodejs using express.
This is my client code:
import json
import clr
clr.AddReference('System')
clr.AddReference('System.IO')
clr.AddReference('System.Net')
from System import Uri
from System.Net import HttpWebRequest
from System.Net import HttpStatusCode
from System.IO import StreamReader, StreamWriter
def post(url, data):
req = HttpWebRequest.Create(Uri(url))
req.Method = "POST"
req.ContentType = "application/json"
json_data = json.dumps(data)
reqStream = req.GetRequestStream()
streamWriter = StreamWriter(reqStream)
streamWriter.Write(json_data)
streamWriter.Flush()
streamWriter.Close()
res = req.GetResponse()
if res.StatusCode == HttpStatusCode.OK:
responseStream = res.GetResponseStream()
reader = StreamReader(responseStream)
responseData = reader.ReadToEnd()
return responseData
res = post('http://localhost:5050/hello', postData)
print(res)
And this is my server code:
const express = require("express");
let app = express();
const PORT = process.env.PORT || 5050;
app.post("/hello", (req, res) => {
console.log("Hi!")
console.log(req.body)
res.json({"message": "Hello World"})
})
app.listen(PORT, () => {
console.log(`Server listening on port ${PORT}`);
});
When I run my client code I get the server's response {"message": "Hello World"}
in the output.
On the server I of course see the log: "Hi!", but the output of the req.body
is undefined
.
I messed with it a lot and I really don't know what the problem is with my code, why can't I get the json that the client sends? Why am I getting undefined
?
I'll be glad to receive your help.
you can use the bodyParser middleware to parse the request body.
you need just add this line:
app.use(express.json())
like this:
const express = require('express')
const PORT = process.env.PORT || 5050;
let app = express();
app.use(express.json()); // <-- here
app.post("/hello", (req, res) => {
console.log("Hi!")
console.log(req.body)
res.json({"message": "Hello World"})
});
app.listen(PORT, () => {
console.log(`Server listening on port ${PORT}`);
});