Nodejs: not going in to the requestify - node.js

When I tried to get the response from the requested URL, I can get only printed statements of 'out' its not going in the requestify and how to get the response from requestify. Can any one tell me what is the error behind this.
console.log('out');
requestify.get('http://www.google.com').then(function(response) {
// Get the response body
console.log('in');
response.getBody();
console.log(response.body);
});
console.log('out');

Did you add
var requestify = require('requestify');
above your code?
Also, due to the async behavior of NodeJS it will probably first display 'out' twice and after you recieved a response from Google it will display the google homepage HTML.

Related

How to modify a response in Electron

Let's say that I'm using a GET request on https://example.com and the response is this:
This is a response message.
How would I modify it in a way so that in my code, so that it can change the response to say something like this:
This is a MODIFIED response message.
For example, if my Electron app were to navigate to https://example.com, the screen would show me the modified content instead of the original content.
Essentially, I am trying to literally modify the request.
I have based my code off of this question but it only shows a proof of concept with a pre-typed Buffer, as in my situation I'd like modify the response instead of outright replacing it. So, my code looks like this:
protocol.interceptBufferProtocol("http", (req, CALLBACK) => {
if(req.url.includes("special url here")) {
var request = net.request({
method: req.method,
headers: req.headers,
url: req.url
});
request.on("response", (rp) => {
var d = [];
rp.on("data", c => d.push(c));
rp.on("end", () => {
var e = Buffer.concat(d);
console.log(e.toString());
// do SOMETHING with 'e', the response, then callback it.
CALLBACK(e);
});
});
request.end();
} else {
// Is supposedly going to carry out the request without interception
protocol.uninterceptProtocol("http");
}
}
This is supposed to manually request the URL, grab the response and return it. Without the protocol event, it works and gives me a response, but after some debugging, this piece of code consistently calls the same URL over and over with no response.
There is also the WebRequest API, but there is no way of modifying the response body, you can only modify the request headers & related content.
I haven't looked fully into Chromium-based solutions, but after looking at this, I'm not sure if it is possible to modify the response so it appears on my app's end in the first place. Additionally, I'm not familiar with the Chromium/Puppeteer messages that get sent all over the place.
Is there an elegant way to have Electron to get a URL response/request, call the URL using the headers/body/etc., then save & modify the response to appear different in Electron?

How to get response body from Express.js server using Supertest?

I started to write some tests for my application and I have issues to read/get response from the server. I tried many things but nothing really worked, can someone help me please ?
// /api/checkCreds
exports.checkCreds = async function(req, res){
//validation
if(!await User.checkCreds(req.body.username, req.body.password)){
var result = {error: true, data: "Incorrect"}
res.sendStatus = 401;
return res.send(JSON.stringify(result));
}
If credentials sent to the server aren't matching, return a response with "Incorrect" message back to the user.
In the test I'm trying to get data from the server to check if properties are matching the expected output.
//test.js
it("We should fail with HTTP code 401 because incorrect data is passed (username='incorrect' password='incorrect')", function(done){
supertest(app)
.post('/api/checkCreds')
.send({username: 'incorrect', password: 'incorrect'})
.expect({error: true, data: "Incorrect"})
.expect(401, done);
});
When ran, test fails because expected properties are different from the response sent by the server, which is an empty object {}.
Any help is appreciated.
You may try changing your first expect to see if you can coax supertest into showing you the actual body that it's comparing to. For example, expect('')
If that doesn't work, there's a version of expect that accepts a function. In that function, you should be able to print out what you are getting in the response body, ie. console.log(res).
It may be that there's some confusion with the JSON return type-- I haven't used that directly. You could try expecting JSON.
Finally, there's a strange paragraph in the documentation that I don't think applies, but I thought I'd mention:
One thing to note with the above statement is that superagent now sends any HTTP error (anything other than a 2XX response code) to the callback as the first argument if you do not add a status code expect (i.e. .expect(302)).
While trying to fix my issue, I noticed that in the HTTP response, Content-Type header was set to text/plain and my server was returning JSON, so that probably was the thing that confused supertest.
I think that res.send() sets the header to text/plain by default and I had to manually set the header value to application/json by using res.type('json'). At that point I was able to read the response body without an issue.
I also learned that res.json() sets the Content-Type header to application/json by default, so you don't need to do it manually like with res.send().
Working code:
// /api/checkCreds
if(!await User.checkCreds(req.body.username, req.body.password)){
var result = {error: true, data: "Incorrect"}
return res.status(401).json(result);
}
//test.js
it("We should fail with HTTP code 401 because incorrect data is passed (username='incorrect' password='incorrect')", function(done){
supertest(app)
.post('/api/checkCreds')
.set('Content-type', 'application/json')
.send({username: 'incorrect', password: 'incorrect'})
.expect(401)
.expect(function(res){
console.log(res.body);
})
.end(done);
});
Feel free to correct me if I stated something that isn't quite right.

sending data from angular to node api

i am beginner so i apologize if my question isn't relevant or easy to fix, but i couldn,t fix my issue yet, for 4 days.
I am working on an api, which will receive data from angular form, then store it with sequelize on a mariadb table.
When i submit my form, which would through the url, post it in the table through the api, i can see that the req.body is defined, and it reachs the api, but yet i have and error in my angular http post which is thrown(error 500).
With postman, i see that my url isn t reachable, i can't figure out so if my error comes from the post angular, or the backend with my model, even if error 500 is for back end.
I tried to redefine my sequelize model, parse and stringify the object i send, try others url...but nothing works.
So here is my function called when the form is submitted,the function formatrequestschedulest return the object i want to post.
onSubmitScheduled(){
let OndemandScheduledRequest = this.formatRequestScheduled(this.selectedHotel, this.selectedCheckInDate, this.selectedCheckOutDate, this.selectedNumber, this.selectedCurrency, this.selectedReportName, this.selectedUser, this.selectedEmail, this.selectedFormat);
console.log(OndemandScheduledRequest);
this.saveScheduledRequest(OndemandScheduledRequest);
return this.openDialog();
}
saveScheduledRequest(onDemandScheduledRequest: OnDemandScheduledRequest){
this.http.post('/api/ScheduledReport', JSON.stringify(onDemandScheduledRequest), {headers: {'Content-Type': 'application/json'}})
.subscribe(res=>{ console.log(res
)
console.log('ok')},
(err) =>
console.log('an error'))
/*console.log(err))*/
}
And here is my api:
var request= require('../controller/ondemandscheduledrequests');
var router = express.Router();
router.get('/getreport',request.create);
router.post('/ScheduledReport',request.create);
I can provide also the error i get, but i don't know if i can join a picture to the question.
I just want to have my form data store to my table, but i get an error 500 instead.
this is the error i get
Use pipe like below and try once
this.http.post('/ScheduledReport', JSON.stringify(onDemandScheduledRequest).pipe().subscribe(val => {
console.log(val, "service");
, {headers: {'Content-Type': 'application/json'}})}

Get headers from a request using Nodejs

I'd like to get the headers form a request (ex: status code, content-lenght, content-type...). My code :
options = {
method:'HEAD'
host:"123.30.xxx.xxx"
port:80
}
http.request(options,(res)->
res.send JSON.stringify(res.headers)
)
but this is not working
Please help me :(
Your JSON is not valid and it appears that you are not instantiating options as a variable prior to it's use. ev0lutions code resolves these issues as well as ending the request.
For info on how to create valid JSON check out this tutorial:
http://www.w3schools.com/json/
You need to call .end() on your http.request() object in order to make your request - see the docs:
With http.request() one must always call req.end() to signify that you're done with the request - even if there is no data being written to the request body.
For example:
var options = {
method:"HEAD",
host:"google.com",
port:80
};
var req = http.request(options,function(res) {
console.log(JSON.stringify(res.headers));
});
req.end();
Another issue in your code is that res doesn't have a .send() method - if you're referring to another res variable (for example, containing the code that you have posted) then your variables will be conflicting. If not, you should double check what you're trying to do here.

Node.js read json from google api

i try to get google suggestion from this url http://suggestqueries.google.com/complete/search?q=bob&client=firefox
when i run the url i get this result : ["bob",["bobby shmurda","bob marley","bobbi kristina","bobbi brown","bobbi kristina brown","bob dylan","bob evans","bobby hurley","bob\u0027s burgers","bob seger"]]
in node.js i used request , heres my code :
var request = require('request');
var url = 'http://suggestqueries.google.com/complete/search?q=bob&client=firefox';
request(url,function(error, response, result){
if(!error){
console.log(result);
}
});
until now everythings work fine
as you can see my output is an array with two values, in above code when i try to get result[1]instead of show array its just show a ".
i dont know why this happen.
probably because you get a String and not a JSON.
try JSON.parse
result = JSON.parse(result)
try to parse it first
var json_data = JSON.parse(result);

Resources