【问题标题】:Unexpected end of JSON input when sending data via ajax通过 ajax 发送数据时 JSON 输入意外结束
【发布时间】:2020-02-29 23:46:51
【问题描述】:
<script>
$.ajax({
    type: "POST",
    url: "http://localhost:3000/xot/us/confirm",
    crossDomain: true,
    dataType : 'json',
    contentType: "application/json; charset=utf-8",
    data:JSON.stringify({
      username:"User"
    }),
    success: function(result, status, xhr) {
      console.log(result.address1);
    },
    error: function(xhr, status, error) {
      console.log(error);
    }
  })
</script>

【问题讨论】:

  • 那么错误是来自服务器端还是客户端?跨域调用,所以您启用了 CORS? crossDomain: true, 通常是 JSONP
  • 请提问,不要只贴代码
  • 数据要么是格式错误的 JSON,要么根本不是 JSON。

标签: javascript node.js mongodb promise


【解决方案1】:

如果你使用 nodejs 作为后端,你应该在那里添加标题

app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header(
    'Access-Control-Allow-Headers',
    'Origin, X-Requested-With, Content-Type, Accept'
);
next();  
});

在 Ajax 请求中.. 你的请求看起来像这样

$.ajax({ 类型:“获取”, url: "http://localhost:3002/category", 跨域:是的, contentType: "应用程序/json; charset=utf-8", 数据:JSON.stringify({ 用户名:“用户” }), 成功:函数(结果,状态,xhr){ 控制台.log(结果); }, 错误:函数(xhr,状态,错误){ 控制台日志(错误); } })

【讨论】:

  • 这仍然不起作用....当我以 json 格式向后端发送一些数据时...它显示相同的错误。CORS 中没有问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-10
  • 1970-01-01
  • 1970-01-01
  • 2015-08-05
  • 2016-08-31
相关资源
最近更新 更多