繁体   English   中英

在javascript中发布请求以json主体来休息api

[英]post request to rest api with json body in javascript

我试图通过jira rest api在我的jira应用程序中添加要发布的注释,使用json正文在html / javascript代码中进行处理,但在发出请求时却遇到以下错误

errorMessages”:[“意外字符('Ã'(代码195)):预期为有效值(数字,字符串,数组,对象,'true','false'或'null')\\ n

{“ errorMessages”:[[位于VALUE_STRING \\ n中的意外输入结束,位于[来源:org.apache.catalina.connector.CoyoteInputStream@7b422cb8;第1行,第159行]]]]}

这是我的代码,请考虑我的URL和凭据是否正确。我在REST Client中尝试使用相同的url,凭据和json主体,并能够对JIRA中的问题添加注释,任何人都可以告诉我哪里做错了?

 <html> <head> <meta charset="ISO-8859-1"> <title>Add Comment JIRA REST API</title> <script type="text/javascript"> function addComment() { var xhttp = new XMLHttpRequest(); var commentJson = '{"body" : “adding comment to the task from client side javascript code”}'; xhttp.onreadystatechange = function() { if (xhttp.readyState == 4) { document.getElementById("demo").innerHTML =xhttp.responseText; } }; xhttp.open("POST", "URL",true); xhttp.setRequestHeader("Content-type", "application/json"); xhttp.setRequestHeader("X-Atlassian-Token", "nocheck"); xhttp.setRequestHeader('Authorization', 'Basic'+btoa('username:password')); xhttp.send(commentJson); } </script> </head> <body> <h2>Adding Comment</h2> <button type="button" onclick="addComment()">Add Comment</button> <p id="demo"> </p> </body> </html> 

似乎您正在传输某些格式无效的数据。 这意味着您需要使用JSON.Stringify()或以UTF-8编码json数据。 大概JSON.Stringify()可以解决这个问题。

这行:

 var commentJson = '{"body" : “adding comment to the task from client side javascript code”}';

...在第二个内部字符串周围有错误的双引号。 确保所有双引号都是直的,而不是左或右双引号,如下所示:

var commentJson = '{"body" : "adding comment to the task from client side javascript code"}';

另外,您可能必须确保您的字符编码匹配,如whiterabbitj建议的那样,但是首先您必须处理使用错误的引号。 看起来您正在使用UTF-8发送,但是服务器将您的数据视为ISO-8859-1。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM