javascript - Angular.js 请求/响应 Node.js

标签 javascript json node.js angularjs request

<小时/>

我正在尝试从我的 Angular.js 请求来自 Node.js 服务器的一些数据。问题是,在数据响应后,我看到一个空白的浏览器窗口,上面打印着我的 json 对象。我希望 angular.js 能够识别响应并停留在页面上。

HTML 表单 - 使用 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 服务器 - 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 = 开始;

Node.js 服务器 - 路由

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"}));
});
}

我正在使用 AngularJS v1.2.24 和 Node.js v0.10.25

Angular 中的console.log(data)永远不会被调用..

最佳答案

您好,请尝试从表单中删除操作方法

来自 ng-submit 文档

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.

因此,通过添加这些内容,您会在提交表单时导致页面刷新。

没有它们,Angular 将为您调用 $event.preventDefault(),这会阻止页面重新加载。

编辑:补充一下,您从服务器看到了正确的数据,因为您正在使用预设数据进行响应,当有人发布到/login 时,这些数据将始终提供。

因此,您的表单当前完全绕过了 Angular,并直接从服务器获取数据。

关于javascript - Angular.js 请求/响应 Node.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25785050/

相关文章:

java - 将 jackson-core-asl 添加到 maven 依赖项导致 ClassNotFoundException

node.js - 在 AWS EC2 上部署 Angular 5 应用程序

javascript - 如何将自定义 ID 与用户名关联起来

javascript - 如何在 MongoDB 连接上修复 'MongoParseError: Multiple text records not allowed at ...'

javascript - 光标位于右侧而不是左侧

javascript - 如何在 javascript 中获取当前日期的一周中的 7 天?

javascript - RGB 到 XYZ 和 LAB 颜色转换

javascript - Node : Update html5 canvas whiteboard using socket. io

json - 将列表添加到 Cloudformation 模板的参数文件中

json - 使用 Aeson 解析有问题的 JSON