在使用 API 与数组参数一起使用时,根据 RESTful 设计原则,我们应该使用 HTTP 方法中的 POST
或 PUT
。
如果我们要创建一个新资源,我们应该使用 POST
方法。这意味着我们将向服务器发送一个包含数组参数的请求,并在服务器上创建一个新的资源。
如果我们要更新一个已有的资源,并使用数组参数来更新其内容,我们应该使用 PUT
方法。这意味着我们将向服务器发送一个包含数组参数的请求,并使用该数组参数更新服务器上已有资源的内容。
以下是使用这两个方法的示例代码:
使用 POST
方法创建新资源:
fetch('/api/resource', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ data: [1, 2, 3] }),
})
.then(response => response.json())
.then(data => {
console.log('New resource created:', data);
})
.catch(error => {
console.error('Error creating resource:', error);
});
使用 PUT
方法更新已有资源:
fetch('/api/resource/123', {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ data: [4, 5, 6] }),
})
.then(response => response.json())
.then(data => {
console.log('Resource updated:', data);
})
.catch(error => {
console.error('Error updating resource:', error);
});
请注意,以上示例中的 /api/resource
和 /api/resource/123
是示意性的 URL,你需要将其替换为你实际的 API 端点。另外,我们还在请求的 headers
中指定了 Content-Type: application/json
,这是为了告诉服务器请求的主体是 JSON 格式的数据。