I am trying to create a Weather API using node. In my controller file, I have this code which is run for the /check route.
controller.js:
//Check Weather
exports.check = (req, res) => {
UserModel.check(req.body.city)
};
model.js:
//Check Weather
function getData(city) {
url = "something";
request(url, function (err, response, body) {
if(err){
console.log('error:', error);
} else {
console.log('body:', body);
}
});
}
exports.check = (city) => {
city = city.toLowerCase();
let values = getData(city);
console.log(city);
return(values);
};
route:
app.post('/check', [
UsersController.check
]);
When I run this, it functions properly and the correct thing is logged in the console. However, after I send a request in Postman and the console.log shows up, Postman seems to be hung up as seen in this pic. Is there anyway I can make it so that Postman stops sending the request after return or console.log?
Postman is waiting for a response from the server. Your code is not currently sending any response, so postman seems 'hung up' as it is waiting. Try changing the line saying UserModel.check(req.body.city) to say res.send(UserModel.check(req.body.city)) so it will send the data returned from your UserModel.check function back as the response. Alternatively, if you don't want to send back the returned value, you could just add res.send(PutWhateverYouWantSentHere) after the function call.
Related
On my webpage user can enter text and press send. this causes the server to append the message to a json object stored in a file. when this file is altered it then sends the new json to the client.
app.post("/recieve",function(req,res){
watcher = fs.watch(__dirname+"/msgs/msg.json", (eventName, filename) => {
watcher.close();
fs.readFile(__dirname+"/msgs/msg.json", (err,data) => {
return res.send(data);
});
});
})
here is the client side
async function recieveMSG(){
$.ajax({
url: "recieve",
type: "POST",
contentType: "text; charset=utf-8"
}).done(function(data){
$("#msgbox").html("<br>"+data+"<br>");
recieveMSG();
});
}
recieveMSG();
As shown in the code above, the client sends a POST request to the server. Next after the json file is changed the server responds to the POST request with the json. I know this may be the completely wrong way to do it, but I want to know why res.send(data) is being called twice on the same res object.
It seems after the first refresh the recieve POST request just doesnot do anything
app.post("/recieve",async function(req,res){
try{
watcher.close();
}
catch(e){
console.log("WatcherUndefined --first execution");
}
watcher = fs.watch(__dirname+"/msgs/msg.json", (eventName, filename) => {
watcher.close();
fs.readFile(__dirname+"/msgs/msg.json", (err,data) => {
return res.send(data);
});
});
})
The problem was that the watcher wasn't getting closed after the client refreshed/disconnected. After the client refreshed the res object generated by their stale request is unusable. I believe that the watcher's callback was never redefined with the new res object (after refresh). I do not know if my assumption is correct, and would like to hear other's thoughts on this as I am new to nodejs.
I am trying to store the response of an http request made using nodejs by request module but the problem is I can't acsess it after the request is completed in more details we can say after the callback
How I can add it
Here is what I tried till now
Tried to use var instead of let
Tried passing it to a function so that i can use it later but no luck
Here is my code can anyone help actually new to nodejs that's why maybe a noob question
var request = require('request')
var response
function sort(body) {
for (var i = 0; i < body.length; i++) {
body[i] = body[i].replace("\r", "");
}
response = body
return response
}
request.get(
"https://api.proxyscrape.com/?request=getproxies&proxytype=http&timeout=10000&country=all&ssl=all&anonymity=all",
(err, res, body) => {
if (err) {
return console.log(err);
}
body = body.split("\n");
sort(body);
}
);
console.log(response)
In this I am fetching up the proxies from this api and trying to store them in a variable called as response
var request = require("request");
var response;
async function sort(body) {
await body.split("\n");
response = await body;
console.log(response); // this console log show you after function process is done.
return response;
}
request.get(
"https://api.proxyscrape.com/?request=getproxies&proxytype=http&timeout=10000&country=all&ssl=all&anonymity=all",
(err, res, body) => {
if (err) {
return console.log(err);
}
sort(body);
}
);
// console.log(response); //This console log runs before the function still on process, so that's why it gives you undefined.
Try this code it works fine I just tested.
put the console log inside the function so you can see the result.
The console.log that you put actually runs before you process the data so that's why you are getting "undefined".
Actually, you will get the data after the sort Function is done processing.
I am trying to build a facebook messenger bot using nodejs. I got the bot developed with core features. While testing for
a negative scenario where the user sends in a GIF or sticker, it has to respond "I couldn't get you. Sorry". It does send
that message but it hangs and keeps sending that message thereafter every few minutes. I noticed that the ngrok server threw an 500 HTTP
Internal Server Error for the POST request. On further debugging, I was able to find out that res.send(200) is not getting executed properly.
The console.log stmt that I have after res.send(200) never gets printed. Not sure what I may be missing. Any help is appreciated. Tried restarting the server and resubscribed to the app with a new ngork https link. The same message continues to get printed out :(.
Here is my code.
server.post('/', (req, res, next) => {
// Extract the body of the POST request
let data = req.body;
let incomingMessage = '';
if(data.object === 'page') {
data.entry.forEach(pageObj => {
// Iterate through the messaging Array
pageObj.messaging.forEach(msgEvent => {
incomingMessage = {
sender: msgEvent.sender.id,
timeOfMessage: msgEvent.timestamp,
message: msgEvent.message
}
});
});
}
const {
message,
sender
} = incomingMessage
if(message.text) {
f.txt(sender, 'Hi there!!!');
} else {
f.txt(sender, `I couldn't get you. Sorry :(`);
//res.send(200);
}
res.send(200);
console.log('We are at the end of post');
return next();
});
Maybe this answer doesn't resolve your problem but it can be helpful.
If you want to send a 200 HTTP code use this instead:
res.sendStatus(200); // equivalent to res.status(200).send('OK')
On the other hand, if this is not a middleware, you can remove the return next(); line.
Background:
I am using building a system which uses 2 different 3rd parties to do something.
3rd party #1 - is facebook messenger app, which requires a webhook to connect and send info via POST() protocol.
3rd party #2 - is a platform which I used to build a bot (called GUPSHUP).
My server is in the middle between them - so, I need to hook the facebook messenger app to my endpoint on MY server (already did), so every message that the Facebook app get's, it sends to MY server.
Now, what I actually need, is that my server to act as "middleware" and simply send the "req" and "res" it gets to the other platform url (let's call it GUPSHUP-URL), get the res back and send it to the Facebook app.
I am not sure how to write such a middleware that acts like this.
My server post function is:
app.post('/webhook', function (req, res) {
/* send to the GUPSHUP-URL , the req,res which I got ,
and get the update(?) req and also res so I can pass them
back like this (I think)
req = GUPSHUP-URL.req
res = GUPSHUP-URL.res
*/
});
Yes , you can pass do request on another server using request module
var request = require('request');
app.post('/webhook', function (req, res) {
/* send to the GUPSHUP-URL , the req,res which I got ,
and get the update(?) req and also res so I can pass them
back like this (I think)
req = GUPSHUP-URL.req
res = GUPSHUP-URL.res
*/
request('GUPSHUP-URL', function (error, response, body) {
if(error){
console.log('error:', error); // Print the error if one occurred
return res.status(400).send(error)
}
console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
console.log('body:', body); // Print the HTML for the Google homepage.
return res.status(200).send(body); //Return to client
});
});
2nd Version
var request = require('request');
//use callback function to pass uper post
function requestToGUPSHUP(url,callback){
request(url, function (error, response, body) {
return callback(error, response, body);
}
app.post('/webhook', function (req, res) {
/* send to the GUPSHUP-URL , the req,res which I got ,
and get the update(?) req and also res so I can pass them
back like this (I think)
req = GUPSHUP-URL.req
res = GUPSHUP-URL.res
*/
requestToGUPSHUP('GUPSHUP-URL',function (error, response, body) {
if(error){
return res.status(400).send(error)
}
//do whatever you want
return res.status(200).send(body); //Return to client
});
});
More info Request module
So, I am creating a REST API using node and I have to create a route.
Purpose of the route: Act as a proxy server and make a call to a different external website and return the response it gets to the original request.
So far, I have the following code and it works:
app.post('/v1/something/:_id/proxy',
function(req, res, next) {
// Basically make a request call to some external website and return
// the response I get from that as my own response
var opts = {/*json containing proper uri, mehtod and json*/}
request(opts, function (error, responseNS, b) {
if(error) return callback(error)
if(!responseNS) return callback(new Error('!response'))
return res.json(responseNS.body)
})
}
)
My question is, how can I stream this http response that I am getting from the external website. By that, I mean that I want to get the response as a stream and keep returning it as soon as it comes in chunks.
Is this possible?
You can pipe the incoming response from an external source straight to a response that your app sends to the browser, like this:
app.post('/v1/something/:_id/proxy',
function(req, res, next) {
// Basically make a request call to some external website and return
// the response I get from that as my own response
var opts = {/*json containing proper uri, mehtod and json*/}
request(opts, function (error, responseNS, b) {
if(error) return callback(error)
if(!responseNS) return callback(new Error('!response'))
return res.json(responseNS.body)
}).pipe(res);
});
With request you can directly pipe incoming response to either file stream, to other requests or to the response that your api sends to the browser. Like
function (req, res, next) {
request
.get('http://example.com/doodle.png')
.pipe(res)
}
Similary in your case just pipe to response.
app.post('/v1/something/:_id/proxy',
function(req, res, next) {
// Basically make a request call to some external website and return
// the response I get from that as my own response
var opts = {/*json containing proper uri, mehtod and json*/}
request(opts, function (error, responseNS, b) {
if(error) return callback(error)
if(!responseNS) return callback(new Error('!response'))
}).pipe(res);
}
)