Amen Ra
Amen Ra

Reputation: 2851

Getting an error when trying to use request.js library in node

I am testing out using request.js in my node/express application. But I keep getting the following error when I run the command node post.js:

events.js:160
  throw er; // Unhandled 'error' event
  ^

Error: Invalid protocol: null
at Request.init (/Users/amenra/Documents/node-apps/learnexpress/node_modules/request/request.js:460:31)
at new Request (/Users/amenra/Documents/node-apps/learnexpress/node_modules/request/request.js:130:8)
at request (/Users/amenra/Documents/node-apps/learnexpress/node_modules/request/index.js:54:10)
at Function.post (/Users/amenra/Documents/node-apps/learnexpress/node_modules/request/index.js:62:12)
at Object.<anonymous> (/Users/amenra/Documents/node-apps/learnexpress/post.js:2:13)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)

Here is my code for my server.js

var express = require('express'),
    parser = require('body-parser'),
    app = new express();

    var data = {
      info: [7,77,88,23,65,66]
    };

    app.use(parser.json());
    app.use(parser.urlencoded({extended: true}));

    app.get('/', function(req, res){
      res.status(200)
        //  .send("Hello World");
        .json(data);
    });

    app.post('/', function(req, res){
      var data = req.body;
      console.log(data);
    });

    app.use('/home', express.static('app'));

    app.listen(9001);
    

And here is my code for post.js:

var request = require('request');
    request.post('http://localhost:9001',{form:{name:"Amen Moja Ra"}})

Why is there an error being thrown?

Upvotes: 0

Views: 246

Answers (2)

Amen Ra
Amen Ra

Reputation: 2851

Since I am on a mac. I had to do the following:

run this command first in terminal A

nodemon server.js

Then run this command in `terminal B'

sudo node post.js

Then check back in terminal A and I will see my data logged in the console.

Upvotes: 0

Alex Hurt
Alex Hurt

Reputation: 86

Your server isn't running when you do that.

Open one terminal and type node server.js

In another terminal: node post.js

Upvotes: 1

Related Questions