Sending POST request to node.js server - html

I have a .net application which sends the following request to a node js server:
System.Net.Http.HttpClient client = new HttpClient();
client.PostAsync("http://some_url.com", some_string);
What I want to do is extract some_string from the post request on my server.
The post request comes in but I am unsure how to get the string from it. What I do:
if (req.method == 'POST') {
var body = '';
req.on('data,', function (data) {
body += data;
console.log(data);
});
But this does not do anything. I can see the length of my data in the req.headers property but where is the data itself? Am I doing this correctly?

Related

When I get JSON data through AJAX, Where does the data get stored?

I want to know the place where certain JSON data get stored when it's sent from server to client which exists in the different directory.
I am trying to build simple API which send JSON data from server side(port number:5001) to client side(port number:3000).
What I noticed doing this project is that http header and body is not the place where the JSON to be contained.
If so, how does JSON data get delivered to client side?
I want to know what happen in code-behind.
Following is the code that I wrote to build simple API:
Client side code:
componentDidMount() {
axios.get('localhost:5001')
.then((result) => console.log(result))
.catch((err) => console.log('Error ocurred'));
}
Server side code(ASP.NET Core 2.0):
UserPosts result = new UserPosts();
result.id = 1;
result.Name = "jay";
result.Password = "1004";
result.Content = "This is text from the server";
string json = JsonConvert.SerializeObject(result);
context.Response.ContentType = "application/json;
charset=utf-8";
await context.Response.WriteAsync(json);
I expected that the JSON data named 'result' will be attached to HTTP header or body but it was not. When I checked the raw data of http body on the console, it was just html content. This is the content displayed on the browser:
{"id":1,"Name":"jay","Password":"1004","Content":"This is text from the server"}
as I wrote in the code, I want this data on the console not on the browser view page.
That seems you get error returned form server side . You should firstly Enable Cross-Origin Requests (CORS) in ASP.NET Core
Add CORS to your web api in ConfigureServices :
services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
}));
And enable that in Configure function :
app.UseCors("MyPolicy");
If you have middleware to modify the response in your web api :
app.Run(async (context) =>
{
UserPosts result = new UserPosts();
result.id = 1;
result.Name = "jay";
result.Password = "1004";
result.Content = "This is text from the server";
string json = JsonConvert.SerializeObject(result);
context.Response.ContentType = "application/json; charset = utf - 8";
await context.Response.WriteAsync(json);
});
In client , you could get the result by accessing .data in response :
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
function test(){
axios.get('http://localhost:5001/api/values')
.then(
(result) => console.log(result.data)
)
.catch(
(err) => console.log('Error ocurred')
);
}
</script>

Ajax GET request works on Chrome but not Firefox or Safari

The following code works fine in Chrome. The route for this get prints out the reportOrder to the terminal. (This is not the final goal but just for testing to make sure the data is received properly). If the request is made in Chrome the server receives the stringified JSON and prints it to the terminal. If the request is made in Safari or Firefox, the server returns a 404 error.
if(formready){
document.getElementById("invalidform").innerHTML = "";
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
};
console.log(this.status);
};
xhttp.open("GET", "/submit/"+JSON.stringify(reportOrder), true);
xhttp.send();
}
else{
document.getElementById("invalidform").innerHTML = "<p style='color: red'>Oops! Please correct all fields marked in red.</p>";
}
I've read a few things about ajax requests being finicky in different browsers but don't understand why the server would return a 404.
Just in case this is helpful here is the route:
app.get("/submit/:data", function(req, res){
var rawFormData = req.params.data;
var formData = JSON.parse(rawFormData);
console.log(formData);
});
To pass parameters in GET URL, it is better to serialize using parameter format, such as using jQuery.param(...) (alias: $.param(...)). OP mentioned that "When I use jQuery.param the GET request gets through on all browsers."
To read the parameters in server side, it's not necessary to write a custom parser. Express has already parsed them and expose as req.query.
For example, if the GET request is sent to URL /submit?a=42&b=88, then in server side req.query would be an object containing property a and b:
app.get('/submit', function(req, res) {
console.log(req.query); // { a: '42', b: '88' }
res.status(200).end();
});
You need full path in get request url.

how to get Json response from my node.js server and display it on web(ejs) page

i want to know how i can get a json response from my node.js server and display the response on my web page
below is the request and reponse in json code
var request = require("request"),
username = req.body.username,
password = req.body.password,
url = "https://api.ecoachsolutions.com/main.php?ecoachsignin=1&server=remote&user="+username+"&pass="+password;
console.log("url is "+url);
request.get(
{
url : url
},
function (error, response, body) {
// Do more stuff with 'body' here
if (!error && response.statusCode == 200) {
var json_body = JSON.parse(body);
console.log(json_body);
var msg = json_body.profile.user;//this is the message i want to show on my web page(msg)
console.log(msg); // get json response
}
}
);
You will first have to register express to use ejs:
app.engine('.html', require('ejs').__express);
then you can use res.render and pass your data to the view
res.render('index.html', {msg: json_body.profile.user});
After that you can access that via the EJS
<%= msg %>
If you need a working example, a good one can be found at:
https://github.com/strongloop/express/tree/master/examples/ejs

Node Express 4 get header in middleware missing

I have a middleware function using Node's Express4 to log each request & response for debugging. I use the res.json call in the request handler to send back JSON to the client for all but static files. So I do not want to log the response for static files, but only the JSON responses. I have the following code:
function logRequests(req, res, next) {
// do logging (will show user name before authentication)
logger.reqLog('IN '+req.method+' '+req.url, req);
var oldEnd = res.end,
oldWrite = res.write,
chunks = [];
res.write = function(chunk) {
chunks.push(chunk);
oldWrite.apply(res, arguments);
};
res.end = function(chunk, encoding) {
if(chunk) {
chunks.push(chunk);
}
oldEnd.apply(res, arguments);
// the content-type prints "undefined" in some cases
// even though the browser shows it returned as "application/json"
console.log('type='+res.get('content-type'));
if(res.get('content-type') === 'application/json') {
var body = Buffer.concat(chunks).toString('utf8');
logger.info(body, req);
}
logger.reqLog('OUT '+req.method+' '+req.path, req);
};
next(); // make sure we go to the next routes and don't stop here
}
So why do some requests show the correct content type in the middleware meaning they also print the response fine and others do not? All of them look good in the REST client when inspecting the returned headers.
EDIT: Some more info discovered tonight while trying to figure this out - if I append any character as a dummy request parameter, it logs the response type correctly:
http://localhost:8081/node/ionmed/api/logout?0 WORKS
where
http://localhost:8081/node/ionmed/api/logout DOES NOT
Also, I can always get a response type logging in the middleware function if I replace the .json() call with .end() so this:
res.json({ item: 'logout', success: true });
becomes:
res.set('content-type', 'application/json');
res.end({ item: 'logout', success: true });

Node: Basic JSON request

I'm a complete beginner in Node.js and I wanted to consult something I could not figure out.
Even though I've researched extensively I could not find any method to receive JSON request without using a plugin. I will be using it to program a mobile application API. But even though I've incluede parameter request I cannot reach the content by using request.body, or request.data. The request I'm trying to make is;
{
"id":"123"
}
And my failing code is;
var http = require('http');
function onRequest(request, response){
console.log("Request: "+request.data+"\n");
response.writeHead(200, {"Content-Type":"text/plain"});
response.write("Hello, World");
response.end();
}
http.createServer(onRequest).listen(8888);
The problem here is that you're not listening to the request events to let you know that you have data, and then parsing the data. You're assuming that request has request.data.
It should be:
var http = require('http');
function onRequest(request, response){
var data = '';
request.setEncoding('utf8');
// Request received data.
request.on('data', function(chunk) {
data += chunk;
});
// The end of the request was reached. Handle the data now.
request.on('end', function() {
console.log("Request: "+data+"\n");
response.writeHead(200, {"Content-Type":"text/plain"});
response.write("Hello, World");
response.end();
});
}
http.createServer(onRequest).listen(8888);
See this for the documentation for the methods that request contains.