Angular $ http POST从ExpressJS

时间:2015-04-29 01:49:14

标签: 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

1 个答案:

答案 0 :(得分:2)

你的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);