angularjs - Angular $http POST 从 ExpressJS 获取空值

标签 angularjs node.js http post express

我在后端和使用 Node 以及尝试设置 $http POST 请求以将表单发送到 Express 方面经验不足。每次发出请求时,我的回调 data 都是 null。也许我的 Express 路由配置不正确?我正在使用 Angular 与 Express/Node 通信以通过 nodemailer(我已经正确配置)发送电子邮件。

这是我的 $http POST 请求:

客户端/服务/emailer/emailer.js

angular.module('public').factory('EmailerService',function($http) {
    return {
            postEmail: function(emailData, callback) {
            console.log('call http with object', emailData);
            $http({
                method: 'POST',
                url: 'http://my-website.com/server/routes/emailer',
                data: emailData,
                headers: { "Content-Type": "application/json" },
                responseType: 'json'
            }).success(function(data, status, headers, config) {
                console.log('success', data, status);
            }).error(function(data, status, headers, config) {
                console.log('error', data, status);
            }).catch(function(error){
                console.log('catch', error);
            });
        }
    };
});

这是我的服务器端 Express 配置:

服务器/路由/emailer.js

var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
var logger = require('morgan');

var app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(logger('dev'));

app.post('/emailer', function(req,res) {
    // NOTHING LOGS HERE
    console.log(res, req, req.body, res.body);
});

module.exports = app;

这里没有任何日志记录到控制台,$http 请求的错误处理返回如下:

emailer.js:4 call http with  Object {email: "asdf"}
angular.js:8632 OPTIONS http://matt-mcdaniel.com/server/routes/emailer net::ERR_CONNECTION_TIMED_OUT(anonymous function) @ angular.js:8632sendReq @ angular.js:8426$get.serverRequest @ angular.js:8146deferred.promise.then.wrappedCallback @ angular.js:11682deferred.promise.then.wrappedCallback @ angular.js:11682(anonymous function) @ angular.js:11768$get.Scope.$eval @ angular.js:12811$get.Scope.$digest @ angular.js:12623$get.Scope.$apply @ angular.js:12915(anonymous function) @ angular.js:19264jQuery.event.dispatch @ jquery.js:4676jQuery.event.add.elemData.handle @ jquery.js:4360
emailer.js:14 error null 0
emailer.js:16 catch Object {data: null, status: 0, headers: function, config: Object, statusText: ""}

为了更好地衡量,并且由于我是学习 Express 的新手,我将发布我的服务器端 app.js

服务器/app.js

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var compression = require('compression');
var routes = require('./routes/index');
var contact = require('./routes/emailer');

var app = express();

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(compression());
app.use(require('connect-livereload')({
    port: 35729,
    ignore: ['.js']
}));

/** Development Settings */
if (app.get('env') === 'development') {
    // This will change in production since we'll be using the dist folder
    app.use(express.static(path.join(__dirname, '../client')));
    // This covers serving up the index page
    // app.use(express.static(path.join(__dirname, '../client/.tmp')));
    // app.use(express.static(path.join(__dirname, '../client/public')));

    // Error Handling
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

/**
 * Production Settings
 */
if (app.get('env') === 'production') {

    // changes it to use the optimized version for production
    app.use(express.static(path.join(__dirname, '/dist')));

    // production error handler
    // no stacktraces leaked to user
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: {}
        });
    });

}

module.exports = app;

app.use(function(req, res) {
    res.sendfile(__dirname + '/dist/index.html');
});

这是我的文件结构:

enter image description here

最佳答案

您的 emailer.js 路径肯定有问题。你应该只在那里有路由逻辑,你不应该重新创建你的快速应用程序。 Express 为您提供了一个 Router 对象来简化此操作。例如,您的 emailer.js 可能如下所示:

module.exports = express.Router()
    .post('/emailer', function(req,res) {
        console.log(res, req, req.body, res.body);
        res.json({hello:'world'});
    });

你可以像这样在 server/app.js 中映射这个路由:

var emailer = require('./routes/emailer');

// ...After all app.use statements, but *before* your error handlers
app.use('/server/routes', emailer);

关于angularjs - Angular $http POST 从 ExpressJS 获取空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29932965/

相关文章:

javascript - ng-transclude 为 : element vs attribute

javascript - Angular Jasmine : View console output from controller?

node.js - Nodejs 和 Express : long time to load page

java - URL 的 commons io 403 但 httpclient 没问题

android - 使用多个 AsyncTask 的同时 HttpClient 请求

javascript - 访问控制允许来源和 Angular.js

javascript - 当选中一个嵌套复选框时,angularjs-make 按钮处于事件状态

javascript - 嵌套查询 - 未定义错误

node.js - socket.io 未向所有客户端发送

perl - 如何在 Perl 中获取 HTTP 状态和 Location header ?