Handling ajax requests, not receiving data - javascript

i'm having a hard time setting up my client-side ajax calls to send data to node express server.
i want to fire my ajax request "onclick" of an href link.
I'm trying to send the ID of the link as a variable to the server, but the server doesn't receive my data (without setInterval)
if i put the ajax request inside a setInterval() (which i don't want to do, because i only want to send the data once a link is clicked to the server),
the server receives the data in res.req.body, why?
client side:
$('.link_group').click(function () {
data = $(this).attr('id');
$.ajax({
type: "POST",
url: "/ajax_handler",
data: {id: data}
});
});
server side
app.post("/ajax_handler", function(req, res) {
res.send({ //works as it should....
user : req.session.user,
data_objekt: req.session.data
});
if(res.req.body) {
console.log(res.req.body);
}
});
Is this even a common way to "catch" the data from client?
if(res.req.body) {...
doesn't seems right, but i don't know how to do it in a smarter way / can't find any good examples.
I'm about to fire 3-4 Ajax other requests to /ajax_handler which leads to my next question: how to handle multiple ajax requests to the same url?
Thanks in advance!

Are you parsing the request? req.body is initially empty/undefined. You will need to pass it to a middleware that parses the data into req.body. Body-parser is a nodejs module that can achieve this. Here's how to a POST request with JSON data being sent.
const bodyParser = require('body-parser')
app.use(bodyParser.json());
app.post("/ajax_handler", function(req, res) {
res.send({ //works as it should....
user : req.session.user,
data_objekt: req.session.data
});
if(req.body) {
console.log(req.body);
}
});

Related

Getting data sent from AJAX on Express server

My code below is sending data across my express server using a AJAX request. I need to access that data once sent, on my express server to do some manipulation. How can I go about doing this?
Express Server Snippet:
app.get("/time",function(req,res){
client.messages.create({
to: "+1" + req.data.number,
from: '+166**',
body: "This is the ship that made the Kessel Run in fourteen parsecs?",
mediaUrl: "https://c1.staticflickr.com/3/2899/14341091933_1e92e62d12_b.jpg",
});
});
Ajax Request:
$.ajax({url: "/time",
data : { name : 'Justin', number : '662***' }
});
If you are talking about the GET variable in the server:
app.get("/time",function(req,res){
client.messages.create({
to: "+1" + req.params.number, // should be `req.params` instead
from: '+166**',
body: "This is the ship that made the Kessel Run in fourteen parsecs?",
mediaUrl: "https://c1.staticflickr.com/3/2899/14341091933_1e92e62d12_b.jpg",
});
console.log(req.params.name)
console.log(req.params.number)
});
If you are saying the response of the server, then:
$.ajax({
url: "/time",
data : { name : 'Justin', number : '662***' }
}).done(function (response) {
console.log(response)
});
I've read the question 3 times, and still couldn't figure out what was being asked, sorry.
If you are trying to send the data to Express, you probably should be doing this with a "POST" method in your Ajax call. Then, having a route just like the one you have, but app.post. You also should use the "body-parser" middleware, before your "post" route.
So, you should have something like this on your server (regarding just what I am saying):
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/time', (req, res) => {
console.log(req.body); // your data here
})
In your Ajax call, just add a 'post' method.
What #joaumg says it's about req.params is also correct, but with a POST seems more correct to me. Your data will be safer.

How to perform a POST request with session data to an endpoint within the server node js

I am working on express and I need to perform a POST request to an endpoint within the server. My code for this is :
request({
url : 'http://localhost:3000/api/oauth2/authorize',
qs:{
transaction_id:req.oauth2.transactionID,
user:req.user,
client : req.oauth2.client
},
headers:{
'Authorization':auth,
'Content-Type':'application/x-www-form-urlencoded'
},
method:'POST'
},function(err,res,bo){
console.log("Got response with body :"+bo);
});
localhost is the current server, this works properly but the session data is lost when i perform the POST request.
Is there any other way to perform a POST within the same server or to save the session data such that it is maintained after the POST?
Well, typically you register your routes something like:
var handlePostRequest = function(req,res,next) {
// process req.body etc.
};
app.post('/api/oauth2/authorize', handlePostRequest);
If you want to call that endpoint from within your application, you simply call handlePostRequest() providing the req, res, next objects as well.
Assuming handlePostRequest is in global scope, or required already; in your example that would be:
app.get('/some/other/endpoint', function(req,res,next){
// override the default req.body with your supplied data
req.body = {
transaction_id: req.oauth2.transactionID,
user: req.user,
client: req.oauth2.client
};
// you may also override req.headers etc. for authorization
// ...
// then call the "api" again with the new values
return handlePostRequest(req,res,next);
});
IF you however strictly want to make a POST request (for some reason), you need to supply the sessionID as well, which will be in your cookie. Then the session data will be available.

Sending data to app.delete in node.js

I am trying to delete a certain input from my database. I cant seem to get the data to come through on an app.delete to know which entry to delete. However app.post gets the data. Here is my code
Client:
let userToDelete = {
data:entryToDelete
}
httpRequest.delete(url, userToDelete)
.then(function (response) {
//...
Server
app.delete('/api/deleteEntry', function(req, res){
console.log('going to delete', req.body);
//...
});
now if I change to httpRequest.post and app.post, req.body console logs the data I send. Does a .delete request not get the data?
RFC2616 says:
The DELETE method requests that the origin server delete the resource
identified by the Request-URI.
Request bodies are not explicitly disallowed for HTTP DELETE requests, but I wouldn't rely on them always being available. You'll have to include some sort of ID or primary key in your request URI, so that your server can pass that along to your database for deletion.

Send response multiple times?

I have a little problem.
I have a node application on a server, that serves a website as control panel for a client based application.
Example:
You click a link on the site
A http request triggers the server to send a command via socket to the client
The client executes this command
The client sends the output of the command back to the server (socket)
That works fine, on time. The second time the server crashes because the header is already sent.
//Comand comes in
app.get('/create/:id/:package', function (req, res) {
if (io.sockets.connected[req.params.id]) {
//Command is sent to client
io.sockets.connected[req.params.id].emit('control', {type: 'create', packageName: req.params.package});
//Output is coming back
socket.on('createOutput', function (data) {
//Response sent back to http request (works once)
res.send(data);
});
}
});
Is there any way to work around this behavior?
You can send the data only once with socket.once:
socket.once('createOutput', function (data) {
//Response sent back to http request (works once)
res.send(data);
})

How to get entire request in node.js

I would like to get the entire request (header and body just as they appear when they arrive at the application) in Node.js. I'm able to get it by reading directly from the socket on connection (example below), but I haven't found a way to associate it with a particular request object as it's processed by the server.
...
var server = http.createServer(app).listen();
server.on('connection', function(socket) {
socket.on('data', function(data) {
console.log(data.toString());
});
});
...
app.get("/", function(req, res) {
//get the data that would be output from the above snippet in this context
//do something with it
});
This is just one example to illustrate what I'm looking for, I'm open to any method to achieve this other than attempting to reconstruct the request from information provided in the request object.

Categories

Resources