为什么$ http.post会返回400错误?

时间:2016-05-05 17:13:20

标签: javascript angularjs node.js express mean-stack

我对MEAN很新,很抱歉,如果这个问题如此明显。我想在点击发送按钮时向联系人发送电子邮件。我处理发送电子邮件的代码是使用我目前使用SendGrid Nodejs API发送电子邮件的帖子。问题是我一直遇到400 Post Error。

This is the error I get in my Google Chrome Console

This is the error I get in my server terminal

这是在我的controller.js:

$scope.send = function(contact) {
    console.log("Controller: Sending message to:"+ contact.email);
    $http.post('/email', contact.email).then(function (response) {
          //  return response;
          refresh();
        });
    };

此代码位于我的server.js:

var express = require("express");
var app = express();
//require the mongojs mondule
var mongojs =  require('mongojs');
//which db and collection we will be using
var db = mongojs('contactlist', ['contactlist']);
//sendgrid with my API Key
var sendgrid = require("sendgrid")("APIKEY");
var email = new sendgrid.Email();
var bodyParser = require('body-parser');
//location of your styles, html, etc
app.use(express.static(__dirname + "/public"));
app.use(bodyParser.json());
    app.post('/email', function (req, res) {
         var curEmail = req.body;
          console.log("Hey I am going to send this person a message:" + curEmail);
      var payload   = {
        to      : 'test@gmail.com',
        from    : 'test1@gmail.com',
        subject : 'Test Email',
        text    : 'This is my first email through SendGrid'
      }
      sendgrid.send(payload, function(err, json) {
      if (err) {
        console.error(err);
      }
      console.log(json);
      });
    });

目前电子邮件是硬编码的,但我会在修复帖子问题后进行更改。如果你能指出我正确的方向,那将是非常有帮助的。谢谢。

2 个答案:

答案 0 :(得分:1)

看起来您期望请求正文包含JSON,使用以下行:

app.use(bodyParser.json());

你的控制台中的错误是Unexpected token,这让我相信身体解析器遇到了无法解析为JSON的东西......可能是一个字符串。这意味着您在请求正文中将您的电子邮件作为字符串发送。

简单的解决方法是更改​​您发送请求客户端的方式:

var data = { email: 'some@email.com' }; // as opposed to just 'some@email.com'

$http.post('/email', data).then(refresh);

答案 1 :(得分:0)

使用此代码

$scope.send = function(contact) {
    console.log("Controller: Sending message to:"+ contact.email);
    $http.post('/email', contact).then(function (response) {
          //  return response;
          refresh();
        });
    };

并在服务器端

app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser());