简体   繁体   中英

Angular.js request/response Node.js


I am trying to request some data from node.js server from my angular.js. The problem is that upon data response i see a blank browser window with my json object printed on it. I want angular.js to recognize the response and stay on page.

HTML form - template that gets loaded with loginController

<section class="small-container">
    <div class="login-form">
        <form action="/login" method="post" ng-submit="processForm()">
            <input ng-model="formData.username" type="text" name="username">
            <input ng-model="formData.password" type="password" name="password">
            <button>login</button>
        </form>
    </div>
</section>

Angular.JS

var app = angular.module("blavor", ['ngRoute']);

app.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
    $routeProvider
        .when("/", {
            templateUrl: "/index",
            controller: "loginController"
        })
        .when("/register", {
            templateUrl: "/register",
            controller: "registerController"
        })
        .otherwise("/");

        $locationProvider.html5Mode(true);
}]);

app.controller('loginController', function($scope, $http) {
    $scope.formData = {};
    $scope.processForm = function() {
        $http({
            method: 'POST',
            url: '/login',
            data: $.param($scope.formData),
            processData: false, 
            responseType: "json",
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        }).success(function(data) {
                console.log(data);
                if (!data.success) {
                    alert("Noo!");
                } else {
                    alert("YEEEY!");
                }
            });
    };
});

Node.js Server - index.js

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var express = require('express');

var bodyParser = require('body-parser');
app.use( bodyParser.json() );
app.use( bodyParser.urlencoded({ extended: false }) );
var routes = require('./routes')(app);
http.listen(3000, function() {
    console.log('listening on *:3000');
});

module.exports.start = start;

Node.js Server - routes

module.exports = function(app) {
app.post('/login', function(request, response) {
console.log(request.body);
    response.setHeader('Content-Type', 'application/json');
    response.end(JSON.stringify({value:"somevalue"}));
});
}

I am using AngularJS v1.2.24 and Node.js v0.10.25

console.log(data) in angular never gets called..

Hi try removing the action and method from your form.

From the ng-submit docs

Enables binding angular expressions to onsubmit events.

Additionally it prevents the default action (which for form means sending the request to the server and reloading the current page), but only if the form does not contain action, data-action, or x-action attributes.

So by adding those, you are causing the page to refresh when the form is submitted.

Without them, angular will call $event.preventDefault() for you, which stops the page from being reloaded.

EDIT: Just to add, you were seeing the correct data from the server because you're responding with preset data, which will always be provided when someone posts to /login.

So your form is currently circumventing angular entirely, and directly getting the data from the server.

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