【发布时间】:2016-08-31 14:02:25
【问题描述】:
我对 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);
});
});
目前电子邮件是硬编码的,但我会在解决帖子问题后进行更改。如果您能指出我正确的方向,那将非常有帮助。谢谢。
【问题讨论】:
-
好像你没有回复
$http.post('/email', contact.email) -
检查您的 POST 请求中的请求标头。当您尝试读取 Content-Type: application/x-www-form-urlencoded as a Content-Type: application/json 时,您遇到的错误很常见
-
当您在 $http.post('/email', contact.email) 中提供您的数据时...您确定 contact.email 是像 { email: 'test@email. com'}。根据错误,问题出在您的请求格式(客户端格式错误)。
-
我相信contact.email是正确的,因为在我把图片打印到谷歌浏览器控制台中,这是正确的电子邮件
-
似乎服务器的数据是 json,但是由于您将电子邮件地址作为第一个字符为 t 的字符串发送(根据错误),它不喜欢它。只需尝试用
JSON.stringify({email: contact.email}};替换contact.email 即可。
标签: javascript angularjs node.js express mean-stack