2016-05-05 13 views
1

私はまったく新しいですので、この質問が非常に明白であれば申し訳ありません。連絡先に送信ボタンをクリックするとメールを送信したい送信電子メールを処理する私のコードは、私は現在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  : '[email protected]', 
     from : '[email protected]', 
     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); 
     }); 
    }); 

現在、電子メールは難しいですコード化されていますが、私はpost issを修正した後に変更を行いますue。あなたが正しい方向に私を指すことができれば、それは非常に役に立つでしょう。ありがとうございました。

+0

は思えます'$ http.post( '/ email'、contact.email)に応答しなかったようです。 – MarkoCen

+0

あなたのPOSTリクエストからリクエストヘッダをチェックしてください。 Content-Type:application/x-www-form-urlencodedをContent-Typeとして読み込もうとしたときに、エラーが発生します。application/json – ruedamanuel

+0

$ http.postでデータを提供すると'/ email'、contact.email)...あなたはcontact.emailが{email: '[email protected]'}のようなオブジェクトであることを確信していますか? エラーによると、問題は要求の形式(クライアント側の構成)にあります。 – Anfelipe

答えて

1

この行で、JSONを格納するためのリクエストボディを期待しているように見えます:

app.use(bodyParser.json()); 

あなたのコンソールであなたの誤差がUnexpected tokenが「ボディ・パーサが、それはcouldn何かが発生したことを信じるように私につながる、と言いますJSONとして解析する...おそらく文字列です。つまり、リクエスト本文に文字列としてメールを送信したことになります。

簡単に修正はあなたが要求クライアント側を送っている方法を変更することです:

var data = { email: '[email protected]' }; // as opposed to just '[email protected]' 

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

'bodyparser.json()'の代わりに 'bodyparser.urlencoded()'を使っても動作しますか? –

+1

@GibryonBhojraj yep!短い答えは、ボディの解析に使用されるメソッドは、ボディのエンコーディングと一致する必要があります。 –

+0

ありがとう、あなたはそれほど効果的です!私は非常に開発するのが初めてです、私はそのコードを凝視していました –

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()); 
関連する問題