简体   繁体   中英

Questions on how to do a basic javascript / node.js HTTP post? Using the request library

Followup #2 : I think this is 99% "my bad" for not properly using a callback (that calls a callback that calls a callback...) idiom of node.js. When I refactor it properly everything seems to work, even in IntelliJ. I even figured out a way to arrange the callback functions that seems vaguely sane to a java programmer. Not sure why it worked on the command line but probably something with how node.js handles the threading/asynch stuff.

Not sure if I should delete this entire question or not.

original question follows:

I'm a veteran Java programmer with next to zero experience in Javascript, node.js, or request. I want to do a basic HTTP GET (and eventually a POST). Mikeal's request framework ( https://github.com/mikeal/request ) looks reasonable. But I can't figure out how to get the response into a variable so it can then be parsed. His examples all have it going to the console.

My code is

var Request = require('request');
var ggg;
Request.get('http://www.google.com', function (error, response, body) {
        console.log(body) // Print the google web page.
        ggg = body;

});

I'm running it in the IntelliJ Webstorm7 debugger. I set a breakpoint within the callback, (at the ggg = body line) which never gets triggered. And, for the record, the console isn't logging anything either. At a breakpoint after this code, ggg is listed as "undefined".

Not sure if this is my misunderstanding, a weirdness in IntelliJ, or that the request library just doesn't work.

Followup : I think something in my intellij is messed up. When I run this code from the command line via node nameoffile.js is seems to work.

Well actually first of all do

npm list

and check if you have request installed...else install using

npm install request

Then you have a simple bug in your code.Your are missing a semicolon after console.log

console.log(body);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM