Node js server not receiving data from angularjs - javascript

I have a data at angularjs client. when i send the data to server using $http.post, i am not able to read data at server. I dont understand where i have gone wrong ?
This is the angular code:
var data = $.param({
id:$scope.user_id,
});
alert(JSON.stringify(data));
$http.post('/getdetails',data)
Here is the node js server code:
app.post('/getdetails',function(req,res){
console.log(req.body);
console.log(req.body.id);
});
output at server log:
{}
undefined
I am not concerned about data i send, i am only concerned whether it is readable at server or not.
Thanks !

You are trying to serialise your data using $.param() which is used only in the GET method and not in post. Just send your JSON data directly to nodeJs like this :
var data = {
id:$scope.user_id,
};
$http.post('/getdetails',data)
In you headers specify :
"Content-Type" : "application/json"
So the final request will be like this :
$http.post('/getdetails',data,{headers : {"Content-Type" : "application/json"}})

Related

Javascript object coming through empty on server side

I have a client-side script running to send the string "Y" to the server. I set up a console.log on the client-side (which you can see below) and another on the server-side. The one on the client-side works, but the one logs an "empty" object.. it just shows "{}".
How do I get my data to stay in the object?
const status = "Y";
const options = {
method: 'POST',
headers: {
'Content-type': 'application/json'
},
body: status
fetch('/events/<%- event.id %>/prompt', options)
console.log(options.body)
Here's my route for context:
router.route('events/:id/prompt')
.get(catchAsync(events.showPrompt))
.post(catchAsync(events.checkIn))
And my controller:
module.exports.checkIn = async(req, res) => {
console.log(req.body);
}
How do I get the object to come through to the server?
For sending "y" as the content and receiving that in Express, you need two things:
You need to make sure the content-type is set to text/plain on the request.
You need the appropriate middleware that will read that text/plain body.
app.use(express.text())
Then, you will find the body in req.body within any express request handler registered after the above middleware.
You could pick different content-types also such as application/json, the corresponding middleware for that content-type app.use(express.json())` and then format the body data in that format.
It's important to realize that Express does not by itself read the body of an incoming request. It reads the headers, but not the body by default. If you want the body to be read, then you need middleware that is looking for whatever content-type the incoming request has, reads the body, parses it from whatever it's format is and puts the resulting parsed data into req.body. Express comes with a number of built-in middleware for popular content-types.
Status is a string. However body have to take a object with key-value pair. If send like with like below, then you get object which contains status on the backend side.
body: {status: status}
Problem from :
Client : you choose Content-type': 'application/json' , so your body must be json format , something like body : { status } . Make sure you sent exact object with browser debug , because some call api package can change value of request.
Server : Some nodejs framework need parse the value is sent from client before read it (Exp : app.use(express.json()) with Express)

Send POST request from JavasScript to Sinatra endpoint

so I have a javascript file that saves a specific value in a variable send that I need to send to my ruby routes file through a POST request. I'm a little confused if I can do this since what I have does not seem to work. I'm using the MVC structure so my routes file is saved in my controllers folder.
In my JS file, I have the following:
var send = "test"`
$.ajax({
url : window.location.href + "senddata/",
type : ",
data : { send: send },
}).done(function(response) {
alert('1');
}).fail(function (error) {
alert('2');
});
In my Ruby file, I'm not sure what to do to be able to receive this data? I know I need to do #variable = params[:send] but not sure from there. I'm using Sinatra.
My ruby code is as follows:
post '/senddata/' do
flash[:success] = "Reached"
end

Problem Posting json data to API using Axios in Vue JS

I am trying to create a Axios request where i will post json data. The format of the data will be
{"qBody":"aaa","qAnswer":"bbb","qOptions":[],"qType":"GAP","qClass":6,"qSubject":1,"qChapter":1,"qCreatorid":1,"qCreatorrole":"admin"}
But it is posting as
{"data":{"qBody":"aaa","qAnswer":"bbb","qOptions":[],"qType":"GAP","qClass":6,"qSubject":1,"qChapter":1,"qCreatorid":1,"qCreatorrole":"admin"}}
Here is my code snippet:
var data = {
"qBody" : question,
"qAnswer" : trueFalseAnswer,
"qOptions" : qOptions,
"qType" : questionCategory,
"qClass" : className,
"qSubject" : subjectName,
"qChapter" : chapterName,
"qCreatorid" : qCreatorid,
"qCreatorrole" : qCreatorrole
};
const newData = JSON.stringify(data)
this.$axios.post("http://128.199.192.87:8081/api/v1/questions/add",{
newData
},{
'Content-Type': "application/json"
}).then((response)=>{
console.log(response)
})
How can I make the format correct? Thanks in advance
What you are console.log()-ing is not what you're sending. It is the response that's getting back from the server. If you want to log what you're sending, use:
console.log(newData);
... just before making the POST request.
Most likely, you don't need to stringify the request.
What you're seeing in the console is the server response. According to the response-schema in their documentation, the server's response data is placed in the .data property of the response object.
So, apparently, the server sends back the same data. With most servers, this means no error has occurred.
In fewer words, you are not sending your data wrapped as { data: ... }. If you were, you would be getting back: { data: { data: ... } }

Angular + PHP: Simplest way to POST an object?

I'm studying php and angular. Currently exploring the possibilities to send data to server side using $http service. This is what I came up with and it seem to work, but it doesn't look elegant.
Angular code:
$http({
method: 'POST',
url: 'server.php',
data: "newUser=" + JSON.stringify(user),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
} // set the headers so angular passing info as form data (not request payload)
})
.success(function (respose) {
var x = JSON.parse(respose);
console.log(JSON.parse(x));
}).error(function (err) {
console.log(err);
console.log("some kind of error");
});
This is my php code to receive the data and return it:
if (isset($_POST["newUser"])) {
$newUser = $_POST["newUser"];
echo json_encode($newUser);
}
Why do I have to specify the name of the json I'm passing? I mean the newUser prefix under the data of the request.
Secondly, why do I have to json.parse twice the response in order to convert it back to a JS Object?
Why to I have to specify the headers in order to pass a simple JSON string?
Q1. Why do I have to specify the name of the json I'm passing? I mean the newUser prefix under the data of the request.
Q3. Why to I have to specify the headers in order to pass a simple JSON string?
In PHP, you have global arrays like $_POST & $_GET to receive the data extracted from the request that are on the form of key=value.
And $_POST is filled when using application/x-www-form-urlencoded or multipart/form-data as the HTTP Content-Type.
So in order to use these global arrays, you have to full-fill these two conditions
Okay the alternative way is to use php://input stream to directly read the raw input, so you can send the json string directly.
file_get_contents(“php://input”);

PUT and POST Request of .save() of Backbonejs model

How to be confirmed whether a backbonejs .save() is sending PUT request ?? I checked my server side, which is working good, there is no problem in server side. But my .save() is not working.
Here is my model of backbone
define(['underscore','backbone'],function(_,Backbone)
{
var my_model = Backbone.Model.extend(
{
urlRoot: "http://localhost/back/server_file.php/number"
});
return my_model;
});
Here is how I am using .save()
var my_data = {
id: data.id,
code: data.code
};
var My_model = new my_model();
My_model.save(my_data,
{
success: function(response)
{
alert('Yes');
},
error: function(response)
{
alert('No');
}
});
I think my .save() is sending POST request to server.
UPDATE
I think I could find out my problem. I am describing that here.
What I would like to do
I would like to send 2 parameters from backbonejs model to server side script (I am using PHP SLIM Framework). Based on those 2 parameters server side script update a record's(2 field of this record match with those 2 parameters ) another field with a static parameter at database.
What backbonejs provide (As I think )
Backbonejs has a model with id as JSON format. Backbonejs sends PUT request to server side script. Server side script just dump (update) the data(which was as JSON format,like a bundle) to the database with matching id. Serer side script would not like to look inside the data.
I am getting (from network tab of firebug) my PUT request URL is like http://localhost/back/server_file.php/number/1 (This is the id) . On the other hand I would like to get URL is like http://localhost/back/server_file.php/number/1 (id the first parameter)/456 (Second parameter).
If I am right, anyone could say how can I implement my plan??
This should work,
My_model.set(my_data);
My_model.save(null, {
wait : true,
url : "http://localhost/back/server_file.php/number/1/456",
success : function(response){
},
error : function(e){
}
});
You can debug the request being sent in network tab of Chrome Developer Tools or you can use a network tool like Fiddler to see all requests.
Refer the attached on where to see the request method being used.

Categories

Resources