How to receive a nodejs data response from ajax - javascript

I am currently learning express, ajax, and nodejs. So currently I am trying to make ajax and nodejs interact with each other. I am sending a client request, using ajax, to a nodejs server. Currently, I am able to invoke app.get in the server correctly, i.e. it works fine until the call to console.log(req.query); at the server side. However, I am having trouble accepting data, that is sent by the server. The client side code does not alert any returned data as I tried to make it to.
This is my code on the client side.
function login(){
var obj = '{"username":"'+$('#username').val()+'", "password":"'+$('#password').val()+'"}';
$.ajax({
type:'GET',
dataType :'json',
data:{"username": $("#username").val(),
"password": $("#password").val()},
url:'http://localhost:10351/function',
success: function (data) {
alert("ajax callaback response:"+JSON.stringify(data));
}
})
This is my code on the server side.
var express = require('express');
var app = express();
var http = require("http");
var server = http.createServer();
var portNumber = 10351;
app.use(express.static('public'));
app.get('/function', function(req, res) {
console.log(req.query);
res.send(JSON.stringify(req.query));
});
app.listen(portNumber, function() {
console.log('Currently listening on port ' + portNumber);
});
Any tips?
I was looking at the answer in the following link:
Node.js, Ajax sending and receiving Json
and I thought maybe i could use response.end and response.setHeader instead?
I'm not quite sure if my problem lies on the client side or the server side.

You don't
Listen to the right port (10901 vs 10351)
Send any parameters in the query section of the url
Need JSON.stringify because you already get a string in (req.query)
You should:
Make the ports match
Send parameters in the url ex:(url:'http://localhost:10351/function?foo=bar)
Remove the stringify ex:
res.send(req.query)
alert("ajax callaback response:"+data);
response.end is not needed if you already use the res.send method, and response.setHeader would be helpful if you want to mark this content as json, so you can put a Content-Type: application/json header,
Or use res.json to do both of these things for you (stringify the json and put the right header for you)

Your ports don't match in code. You said your call worked until console.log(), if the ports don't match it won't even enter app.get() in server.
I think you just posted a different code for client.
I will suggest you to try postman which is chrome extension that will be really helpful to send and get ajax request responses. Using you code just by changing the port number I am able to get the response in postman.

Related

GET request working through Postman but the browser tells me GET request cannot have body

I'm simply trying to send some urlencoded parameters via a GET request using fetch. I'm just trying to print the parameters using Express at the moment, like so:
app.get('/api', function (req, res) {
console.log(req.body);
res.sendStatus(200);
return;
});
This works just fine in Postman using a GET request and x-www-form-urlencoded key-value pairs. The webserver will print all the key-value pairs just fine.
But when I try and use fetch to do the exact same thing I get nothing but problems. I've tried two different methods:
fetch(`http://localhost:3000/api?user=test&password=123`, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
The request does go through using this method, but the webserver only prints {} - an empty object.
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/x-www-form-urlencoded");
var urlencoded = new URLSearchParams();
urlencoded.append("user", "test");
urlencoded.append("password", "123");
var requestOptions = {
method: 'GET',
headers: myHeaders,
body: urlencoded,
};
fetch("localhost:3000/api", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
The request does not go through using this method, and the browser gives me the error TypeError: Window.fetch: HEAD or GET Request cannot have a body.
This code was generated using the request that works in Postman using the generate code snippets option.
What am I doing wrong?
The parameters in this URL:
http://localhost:3000/api?user=test&password=123
are in the query string, not in the body and thus the content-type does not apply to them - they are properly encoded to be in a URL. In Express, you would access these with req.query. You should see a value for req.query.user and req.query.password in your Exprss request handler.
Note, it is not recommended that you send user credentials in a URL like this because URLs are often present in log files at your ISP, at the recipient server, in proxies, in your browser history, etc... User credentials like this should be sent in POST request over https where the credentials would go encoded in the body (where it won't be logged or saved by intermediaries).
The fetch error is accurate. GET requests do not have a body sent with them. That would be for POST or PUT requests. A GET request is a "get" request for a resource that you specify only with a URL.
You're confusing request body with a query string.
Your second request (you don't need a Content-Type for it)
fetch("http://localhost:3000/api?user=test&password=123");
would be handled by the following Express function:
app.get('/api', function (req, res) {
console.log(req.query); // Note that query, not body is used.
res.sendStatus(200);
return;
});
You can access fields from the query object as req.query.user && req.query.password.
As for having a request body in a GET request: while RFC doesn't explicitly fordbid it, it requires server to not change response based on the contents of the body, i.e. the body in GET has no meaning in the standard, so JS HTTP APIs (both fetch & XmlHttpRequest) deny it.
firstly if you are trying to get some data from your API or others API you should do GET request in order to get your desired data from server for example, if you want to get a specific things like a user or something else you can pass your data in GET request URL using query string or route params.
secondly, if you want to authenticate and send your credentials to the server its not recommended to use GET request as i said earlier GET request simply is for fetching some data from server, so if you want to send your credential or anything else you are better off using POST request to send data to the server and you can't do POST request in the browser, so you have to use something like postman or insomnia in order to send your POST request to the server. i hope it could help you to solve your issue.

Python code not being executed with Ajax get request

I have this python code:
from twilio.rest import Client
account_sid = "myID"
auth_token = "myAuth"
client = Client(account_sid, auth_token)
client.api.account.messages.create(
to="+num1",
from_="num2",
body="Hello there!")
and when I execute it on the command line python file.py everything works fine,(aka a text is sent to my phone) but I want to execute this code from a javascript file and I am doing this:
$.ajax({
type: "GET",
url: "file.py",
}).done(function( o ) {
console.error("WOW")
});
but the python is not being executed although I do see the console error. I'm not too sure whats going on, I'm wondering if this needs to be changed to a POST request, but that simply gives me a 404 not found error.
I don't think we can give a python filename as url value. AJAX will send a request to the server and in order to handle that request we will need a server side scripting language.
Below link explains how to handle AJAX request in Django.
How do I integrate Ajax with Django applications?

Update UI in real time with angular and express

I have two UIs, one for order.html and one for ledger.html running on two different ports 3000 and 8000 on localhost . On the order page, a user can place an order for an item. Once he places the order, the information is sent as a POST request to server on port 8000.
Below is the post request from the order.html page to server with port 8000
$scope.sendPostRequest=function(){
var dataToBeSent = $scope.postData;
$http({
method: 'POST',
url: 'http://127.0.0.1:8000/receiveOrder',
headers: { 'Content-Type': 'text/plain' },
data: 'some random data'
}).then(function successCallback(response) {
//extracts key:value pairs from the json sent back
$scope.postResponse= someResponse
}, function errorCallback(error) {
// some error handler functions here
})
}
Below is the express code at port 8000 to receive the above request.
app.post('/receiveOrder', function(req, res){
console.log('type of request '+Type(req));
//extract the text passed in data section of the post request
//TODO: Use the data received to update the dashboard, ledger.html
//send some response back as confirmation
});
Once the POST request is received and the data sent is parsed using body-parser, I need to update the UI of ledger.html page to show this.
Basically, ledger.html keeps track of the orders placed by users in real time. It is a dashboard in which fresh orders keep getting added as they are placed. I am stuck in achieving the above.
I have experimented with using socket.io by way of using event-emitters but could not go very far. I have a schema setup for the order data in MongoDB as well in case I need it.
May I have some guidance about what I can use to achieve the above.

HTTP Request Redirection in angular and node/express

Suppose that I have following angular http request which redirects to a route in the server side (node/express) to perform another http request to web api.
Based on the following code:
Would the angular http request will ever have errorCallback? If yes, under what situation?
What is a possible condition for the if(error) to produce an error in the server side http request? Is it client side http error? Any other else?
Should the http request in server side have error as true, will the app crash?
Angular http request:
$http({
method: 'GET',
url: 'webServerUrl'
}).then(function successCallback(response) {
alert('success');
}, function errorCallback(response) {
alert('fail');
});
Server side http request
var request = require('request');
exports.getSearchResults = function (req, res) {
request({
method: 'POST',
url: 'apiUrl'
}
, function (error, response, body) {
if (error) {
res.jsonp('Unknown error. Please try again later');
}
else {
res.jsonp(body);
}
}
)}
Would the angular http request will ever have errorCallback? If yes, under what situation?
Yes. If the request to the server times out or fails, it will be called.
What is a possible condition for the if(error) to produce an error in the server side http request? Is it client side http error? Any other else?
No, it will only cause an error if the call to the api fails.
Should the http request in server side have error as true, will the app crash?
No, it shouldn't. The error object is an object, not a boolean.
By the way, you should know that it is not standard practice to issue a GET request in the client and then issue a POST request to your api. A POST request implies some sort of state change, whereas a GET should not. Either make them all GET, if the calls can be made repeatedly without any side effects, or make them all POST.

Sending URL with Nodejs and Get Response

Hey guys can someone help me with that issue
im new on node.js and im studing and starting a project.
what i need to do is:
i need to send an url to a webservice and get the response from the webservice, for example:
i send http://www.webservice.com.br/getserver?user=myuser&password=mypassword
after that the webservice will give me a response at his page a succes/error message or a new url for login example http://history.webservice.com.br
so i need to get the response after sending an url someone know how can i do that with node.js ?
in php would be something like that
/*
* $sendurl = "myUrlHere";
* $getserver = file($sendurl);
* var_dump($getserver);
*/
in this php example i send the url and i get the response withou leaving my page.
if someone know how i do that in node or give me a way i will appreciate.
Thank you so much.
First of all, sending username passwords directly in url get requests is a disaster! By the way, I think you are just playing around with node, so this is forgivable ;) Following is a sample code for you to do http requests to your web service:
var http = require('http');
http.get("http://www.webservice.com.br/getserver?user=myuser&password=mypassword", function(res) {
//this is http response status code
console.log(res.statusCode);
//this is headers
console.log(res.headers);
res.setEncoding('utf8');
res.on("data", function(chunk) {
//this is body
console.log(chunk);
});
}).on('error', function(e) {
console.log("Got error: " + e.message);
});

Categories

Resources