thatWiseGuy thatWiseGuy - 3 months ago 56
Node.js Question

Sending POST form data from AngularJS client to Express/Node.js server

I am trying to read data from an AngularJS form and send it to an Express server. My client function to send the data does execute, but the request never reaches the server. I believe there is an issue with the URLs.

Relevant part of my AngularJS controller:

$scope.loginUser = function() {
$scope.statusMsg = 'Sending data to server...';
$http({
url: 'http://##.##.##.##/login.js', // IP address replaced with ##'s
method: 'POST',
data: user,
headers: {'Content-Type': 'application/json'}
})


This does execute, because I see the message appear from the first line. The
url
is the absolute path of my Express server. What should this URL be? (Does it need to point to some existing file?)

Relevant part of my Express server (
login.js
in the same directory):

var express = require("express");
var bodyParser = require("body-parser");
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.post('*', function(req, res) {
console.log('Processing request...');
res.sendFile('/success.html');
});

app.listen(3000);


I execute this server, and it listens on port 3000 as it should. But when my client executes, the
app.post
method above never runs, because I never see the
Processing request...
output on the console. What should the path here be? Does it need to agree with the URL in the client?

What is the issue here? I believe the overall structure is OK, but what should the paths/URLs be? (i.e., not just their values for the case above, but their semantics. The online documentation didn't make this clear.)

If it helps, my HTML form uses
method="post"
and no
action
specified. I have adjusted these and many other settings with no luck.

Answer

The answer is a combination of the answers listed.

  1. Do not list the extension of the Express server in the URL.
  2. Include port number as :3000 immediately following the IP address.

AngularJS client:

url: 'http://##.##.##.##:3000/login'

Express server route:

 app.post('/login', function(req, res) {
     console.log('Processing request...');
     res.sendFile('/success.html');
 });

I also found out that the security group for my Amazon Web Services instance was blocking incoming traffic on port 3000. My application worked after I opened this port to the outside world.

Comments