解决办法:
function REDCapImportRecord() {
const url = 'https://redcap.INSTITUTION.edu/api/'
const testdata = [{
record_id: 'TEST123456',
testfield: 'test'
}]
const body = new FormData();
body.append('token', 'MYTOKEN');
body.append('content', 'record');
body.append('format', 'json');
body.append('data', JSON.stringify(testdata));
const params = {
method: 'POST',
body,
}
return fetch(url, params)
.then(data => {
console.log('fetch data: ', data)
})
.catch(error => console.log('Error: ', error))
}原题:
我正在创建一个与REDCap接口的,并且在使用Javascript中的API时遇到了困难。
我已经启用了REDCap上的所有特权,并且能够使用REDCap和REDCap API游乐场成功地进行调用。
对于这个应用程序,我使用的是fetch:
async function REDCapImport() {
const url = 'https://redcap.med.INSTITUTION.edu/api/'
const testdata = {
record_id: 'TEST1234',
test_field: 'TEST'
}
const params = {
method: 'POST',
token: 'MYTOKEN',
content: 'record',
format: 'json',
type: 'flat',
overwriteBehavior: 'normal',
forceAutoNumber: false,
data: JSON.stringify(testdata),
returnContent: 'count',
returnFormat: 'json',
}
return await fetch(url, params)
.then(data => {
console.log('fetch data: ', data)
})
.then(response => console.log('Response: ', response))
.catch(error => console.log('Error: ', error))
}
}下面是工作的PHP:
<?php
$data = array(
'token' => 'MYTOKEN',
'content' => 'record',
'format' => 'json',
'type' => 'flat',
'overwriteBehavior' => 'normal',
'forceAutoNumber' => 'false',
'data' => $testdata,
'returnContent' => 'count',
'returnFormat' => 'json'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://redcap.med.upenn.edu/api/');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_VERBOSE, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data, '', '&'));
$output = curl_exec($ch);
print $output;
curl_close($ch);我得到一个403错误:

即使在params对象中,如果删除API令牌,它也不会更改错误--它仍然返回403。
它在PHP中运行得很好,所以我觉得我做错了什么,因为我的令牌和特权确实有效。
任何关于如何让这个请求在Javascript中工作的帮助都将不胜感激。谢谢!
发布于 2019-06-08 14:46:45
您将数据放在js中的错误位置。取()方法的第二个参数是一个设置对象,而不是直接的数据对象。您的数据需要转到该设置对象的属性上,特别是body属性。它可以在几个不同的结构blob,FormData,查询字符串等。
所以你会做这样的事情:
let data = new FormData();
data.append('token','your token');
data.append('format','json');
data.append('data',JSON.stringify(testData));
/* etc, keep appending all your data */
let settings={
method:'post',
body:data
};
fetch('url',settings)https://stackoverflow.com/questions/56503719
复制相似问题