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

我对“平均数”相当陌生,如果这个问题如此明显,那么很抱歉。 我想要发送电子邮件给联系人,当他们点击一个发送button。 我处理发送电子邮件的代码是使用一个post,我正在使用SendGrid Nodejs API来发送电子邮件。 问题是我一直运行到400 Post Error。

这是我在Google Chrome控制台中遇到的错误

这是我在服务器端得到的错误

这是在我的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); }); }); 

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

看起来你期待的请求正文包含JSON,这一行:

 app.use(bodyParser.json()); 

你的控制台中的错误说Unexpected token ,这导致我相信身体分析器遇到了不能parsing为JSON的东西…可能是一个string。 这意味着您在请求正文中将您的电子邮件作为string发送。

简单的解决办法是改变你发送请求客户端的方式:

 var data = { email: 'some@email.com' }; // as opposed to just 'some@email.com' $http.post('/email', data).then(refresh); 

使用这个代码

 $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());