【问题标题】:Making a POST request to an API in JavaScript/jQuery在 JavaScript/jQuery 中向 API 发出 POST 请求
【发布时间】:2019-03-12 23:40:19
【问题描述】:

我一直在尝试从 API 获取 POST 请求,但我没有那么幸运地推动它通过。我想知道是不是因为我传递的参数之一是一个对象数组。一直试图让它工作几个小时,但没有运气。

这个post函数需要两个参数,userId和classId。

//这是我调用的api,显然不是实际的URL

let apisource = www.exampleapi.com

//这是类

let classId = 12345;

//这是班上的学生

let userArray = [{
  "name": "user1",
  "userId": 101
}, {
  "name": "user2",
  "userId": 102
}]

我正在编写一个函数,它接受这个 userArray 并将它匹配到一个包含 userIds 的类。

到目前为止,这是我的 API 调用:

function getStudents(classId, userArray) {
  $.post(apisource) + "classes"), {
    userId: userArray.userId,
    classId: classId
  }, function(data, status) {
    console.log("students in class loaded)
  }
}

什么都没有加载。有人对我可能做错的事情有任何建议或指示吗?

【问题讨论】:

  • 您是否使用浏览器的 DevTools 来查看是否有错误以及是否发送了请求?了解这一点很重要
  • 请求甚至没有通过。我想我遗漏了一些东西,或者我写错了一些东西。
  • 你在哪里调用getStudents函数?
  • 我认为你应该将) 之后的apisource 移动到函数的末尾
  • 1.代码有语法错误 2. 从另一个域请求某些东西需要以http:// 开头的 URL 3. 它还需要支持 CORS 请求

标签: javascript jquery ajax post request


【解决方案1】:

这里有几个问题。

例如:

userArray.userId

这部分代码绝对无效。例如,数组有索引,而不是像对象这样的键。这意味着您无法访问 userId 参数,因为您尚未定义它在哪个索引中。

考虑到你的数组有两个项目:

let userArray = [
  { name: 'user1', userId: 101 }, // index 0
  { name: 'user2', userId: 102 } // index 1
];

您需要通过以下方式访问用户 ID:

userArray[0].userId // Returns 101
userArray[1].userId // Returns 102

至于请求本身,它可能看起来像这样:

let apisource = www.exampleapi.com;
let classId = 12345;
$.ajax({  
   type: 'POST',
   url:  apisource,
   data: JSON.stringify({ userId: userArray[0].userId, classId: classId }),
   contentType: "application/json"
});

【讨论】:

  • 如果要发布JSON,需要设置content-type
【解决方案2】:

首先,您无法访问 userArrayuserId 属性,您需要先选择对象,例如“userArray[0].userId”或任何逻辑得到一个元素。

另一方面,我建议你使用 fetch 功能,更容易使用,代码看起来更干净。

var apisource = 'https://example.com/';
var data = {}; // the user picked

fetch(apisource , {
  method: 'POST', // or 'PUT'
  body: JSON.stringify(data), // data can be `string` or {object}!
  headers:{
    'Content-Type': 'application/json'
  }
}).then(res => res.json())
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', response));

来源:https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API

【讨论】:

  • 我会把你的catch 移到最后,否则它会将被拒绝的承诺变成已解决的承诺
  • 不是真的,我同意你将 catch 移到最后,但不是因为这个原因,catch 将在 Promise 真正被拒绝时执行,无论顺序如何。来源:developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
  • 这不正确。如果承诺链在fetch()res.json() 阶段被拒绝,catch 将捕获该拒绝,记录错误,然后因为它没有throw 另一个错误或返回被拒绝的承诺,你的最后一个@ 987654330@ 将像一切正常一样执行
  • 这里有一个小JSFiddle demo 给你。尝试将catch 换到最后,你会看到不同
  • 哦,你是对的,这真是一种奇怪的行为。但感谢菲尔斯的信息。 - 干杯。
【解决方案3】:

看来您需要以这种方式重构您的后期实现以避免一些语法错误。

function getStudents(classId, userArray) {
  $.post( apisource + "classes", { 
    userId: userArray.userId,
    classId: classId 
  })
  .done(function( data, status ) {
    console.log("students in class loaded")
  });
}

【讨论】:

  • 谢谢,帮了大忙!
猜你喜欢
  • 1970-01-01
  • 2021-09-05
  • 1970-01-01
  • 1970-01-01
  • 2021-07-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多