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

Why does my $http.post return a 400 error?

本文关键字:一个 错误 我的 http post 返回 为什么      更新时间:2023-09-26

我对MEAN还很陌生,如果这个问题太明显,我很抱歉。我想在联系人单击发送按钮时向他们发送电子邮件。我处理发送电子邮件的代码是使用一篇我目前正在使用SendGrid Nodejs API发送电子邮件的帖子。问题是我一直遇到一个400后错误。

这是我在谷歌Chrome控制台中得到的错误

这是我在服务器终端中遇到的错误

这在我的控制器js:中

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

这段代码在我的服务器.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,这让我相信主体解析器遇到了无法解析为JSON的东西。。。可能是一串。这意味着您在请求正文中以字符串形式发送了电子邮件。

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

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