我有一个JSON数组,我试图使用Ajax发布到SENDGRID。使用Postman我能够发布没有问题但是当我在.js文件中发布数据时,我不断收到错误(错误请求=缺少参数)。
感谢任何帮助。
注意:这些值实际上是有效的。为了安全起见,我删除了识别信息。
CHROME PAYLOAD:
AJAX致电:
var mailUrl = "https://api.sendgrid.com/v3/mail/send";
var postdata = '{"personalizations": [{"to":[{"to email"}],"from": {"email":"from email"},"subject":"Hello, World!" , "content" : [{ "type":"text/plain" , "value":"TestMessage!" }]}]}'
$.ajax({
type: 'POST',
headers: {Authorization: "Bearer APIKEY"},
url: mailUrl,
contentType: "application/json",
data: JSON.stringify(postdata),
success: function (res) {
alert('ok');
},
error: function (res) {
alert('problems');
}
});
答案 0 :(得分:0)
The string stored in the variable is a valid JSON. Calling JSON.stringify()
on a JSON will escape all the special characters like "
and that escaped string will not be deserialized to the object you intended.
While a string is still a valid JSON according to some specifications, The specifications for application/json
stated in RFC4627
An object structure is represented as a pair of curly brackets surrounding zero or more name/value pairs (or members).
make the returned string invalid for post.
Sending the string itself without serializing it again will likely work.
答案 1 :(得分:0)
问题似乎在于json [{"to":[{"to email"}]
的这一部分。您可以使用jsonlint来验证json。此外,JSON.stringify()
方法将JavaScript值转换为JSON字符串。
但在你的情况下,postdata
已经是一个字符串。