Calling an internal API from within Express - javascript

I have a simple API route set up in Express (consumed mainly via my Angular frontend):
app.post('/api/sendEmail', emailApi.sendEmail);
I've made a module that sits in my backend and also needs to call this service. I figured the easiest way was to do a POST request:
request({
url: '/api/sendEmail',
method: 'POST',
json: {
template: template.toLowerCase(),
obj: mailObj
}
}, function(error, response, body){
console.log('error', error);
console.log('response', response);
console.log('body', body);
});
However, I get this error:
Error: Invalid URI "/api/sendEmail"
What am I doing wrong here?

Change Url to'http://127.0.0.1:3000/api/sendEmail', because you're
calling an internal api with in express or you can also use localhost
in place of 127.0.0.1.
request({
url: 'http://127.0.0.1:3000/api/sendEmail', //on 3000 put your port no.
method: 'POST',
json: {
template: template.toLowerCase(),
obj: mailObj
}
}, function (error, response, body) {
console.log({error: error, response: response, body: body});
});

emailApi.sendEmail is just a function. You are much better off calling it directly. Using the network in this manner would be a serious waste of resources.
On a practical note, there are some complex issues about how to address yourself on the network. Usually you can accomplish this via localhost, but there's no guarantee that the server is listening at that address. So you'll have to take that into account.

You need to use an absolute URI (including the protocol, domain, and port if it's not listening on the default port).
For example, if you know that the server will be listening at localhost:3000, you would want to replace your url value with 'http://localhost:3000/api/sendEmail'.

Assuming you are not using a web server like nginx and are developing on localhost. The express app does not know from where the request has originated. Try setting your Url as http://localhost:300/api/sendEmail.

Related

Node.js - How to send sessionID to GET method in Express via request package? [duplicate]

I'm trying to use NodeJS to scrape a website that requires a login by POST.
Then once I'm logged in I can access a separate webpage by GET.
The first problem right now is logging in. I've tried to use request to POST the login information, but the response I get does not appear to be logged in.
exports.getstats = function (req, res) {
request.post({url : requesturl, form: lform}, function(err, response, body) {
res.writeHeader(200, {"Content-Type": "text/html"});
res.write(body);
res.end();
});
};
Here I'm just forwarding the page I get back, but the page I get back still shows the login form, and if I try to access another page it says I'm not logged in.
I think I need to maintain the client side session and cookie data, but I can find no resources to help me understand how to do that.
As a followup I ended up using zombiejs to get the functionality I needed
You need to make a cookie jar and use the same jar for all related requests.
var cookieJar = request.jar();
request.post({url : requesturl, jar: cookieJar, form: lform}, ...
That should in theory allow you to scrape pages with GET as a logged-in user, but only once you get the actual login code working. Based on your description of the response to your login POST, that may not be actually working correctly yet, so the cookie jar won't help until you fix the problems in your login code first.
The request.jar(); didn't work for me. So I am using the headers response to make another request like this:
request.post({
url: 'https://exampleurl.com/login',
form: {"login":"xxxx", "password":"xxxx"}
}, function(error, response, body){
request.get({
url:"https://exampleurl.com/logged",
header: response.headers
},function(error, response, body){
// The full html of the authenticated page
console.log(body);
});
});
Actualy this way is working fine. =D
Request manages cookies between requests if you enable it:
Cookies are disabled by default (else, they would be used in
subsequent requests). To enable cookies, set jar to true (either in
defaults or options).
const request = request.defaults({jar: true})
request('http://www.google.com', function () {
request('http://images.google.com')
});

Ajax request not working in loopback

I am beginner in loopback and working on Get Post in loopback
This is code on client side
var datas = 'Something';
$.ajax({
type: 'POST',
url: '/post',
data: datas,
dataType: 'text'
})
.done(function(data) {
console.log('Successful');
.fail(function(jqXhr) {
console.log('Failed');
});
and this is on server side(server.js)
app.post('/post', function(req, res){
console.log('This is DATA '+ req.body);
});
This is not working it gives me 404 not found or failed.
What am I doing wrong and Is there another method for get post in loopback?
the server side needs an server and listening a port.
the client side needs to listen another port.
so they are not in one domain and cannot get access to each other.
this called a "cross-origin requests"
check this for the solution:https://www.w3.org/TR/cors/
Your URL starts with '/'.
Whenever a URL starts with '/' it is treated as absolute URL.
Whereas, most of the time, web apps are bounded with a context root.
Try using URL without initial '/' and it should work.

jquery $.ajax gives 404 not found. Im using node.js with express

This jquery:
$.ajax({
method: "post",
data: JSON.stringify(data),
contentType: "application/json",
url: "http://localhost:3000/ajax"
});
is giving error 404 not found. Here is my server side:
router.get('/ajax', function(req, res ,ext){
var strings = ["rad", "bla", "ska"]
console.log('body: ' + JSON.stringify(req.body));
console.log("AJAX RECEIVED");
res.send(strings);
});
so i do have the /ajax route. When i go to http://localhost:3000/ajax im able to acccess the site . However, when I try to access it with the ajax method I get the 404 error. So im wondering if the error could be with my code, or if it could be the firewall on my computer. Im actually using a company computer that has a firewall that blocks certain sites and I cannot disable it.
If you want to do a HTTP POST, use router.post, not router.get.
your $.ajax call is using POST but your route in express.js is only listening for GET requests.
When you hit the URL through the browser it's doing a GET, so it worked.
You would need to set up a route for POST with router.post('/ajax', ...)

How to "get" from NodeJS with AngularJS

I started an AngularJs App and to retrieve some data from database I'm using NodeJS (totally new to me), on the console of NodeJS it works and also typing the URL directly in the browser but when I try to get the information needed using http.get() in AngularJS using the same URL in the browser I get 404 not found.
I figured it would be a cors problem so I added
require('cors') in the nodeJS app and still doesn't work
Can anyone help me with that ?
Am I right making separate apps for Angularjs in front-end and NodeJS in the Backend or should I assemble them in only one application ?
Thank you for your help
This is the AngularJS code:
$scope.keyLoad = function () {
$http.get("localhost:8080/product")
.success(function (response) {
$scope.keys = response;
console.log(response)
})
};
$scope.keyLoad();
I get 404 not found. I figured it would be a cors problem
If it says it is a 404 error then it is a 404 error and not a CORS problem.
Look at your code:
$http.get("localhost:8080/product")
That URL is missing the scheme. It is a relative URL.
You are going to be requesting something like http://example.com/myapp/localhost:8080/product.
Put http:// or https:// in front of it.
You should use $http service.
For example:
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
Or
$http.get('/someUrl', config).then(successCallback, errorCallback);

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.

Categories

Resources