在我的 React 应用程序中,我有以下 API POST 来允许用户编辑他们的个人资料(名称和图像)。
static updateProfile(formData, user_id) {
const request = new Request(`http://localhost:4300/api/v1/profiles/${user_id}`, {
headers: new Headers({
'Authorization': getBearerToken()
}),
mode: 'no-cors',
method: "POST",
body: formData
});
return fetch(request).then(response => {
return response.json();
}).catch(error => {
return error;
});
}
Run Code Online (Sandbox Code Playgroud)
上述问题是带有授权令牌的标头未在 POST 中发送...
如何获取要在上面的获取请求中发送的授权标头?
仅供参考,对于非多部分表单,授权令牌已成功发送,如下所示:
static loadProfile(user_id) {
const request = new Request(`http://localhost:4300/api/v1/profiles/${user_id}`, {
headers: new Headers({
'Authorization': getBearerToken(),
'Accept' : 'application/json',
'Content-Type' : 'application/json',
})
});
return fetch(request).then(response => {
return response.json();
}).catch(error => {
return error; …Run Code Online (Sandbox Code Playgroud) 如何知道Fetch API中的响应类型?
在 XMLHttpRequest 中,有一个responseType属性指示返回的响应正文的类型(json、text、blob 等)。虽然在Fetch API 响应中,尽管有一些有用的方法来解析其主体(json()、text()、blob()等),但我仍然没有找到任何像 XMLHttpRequest 的responseType属性一样的属性来指示响应的类型。
我正在使用以下获取 API 来获取 API 结果。我需要在状态中设置结果数据,但“this”对象在回调函数中不可用。如何通过访问this关键字更新代码以设置状态中的值?
fetch(config.apiUrl + '/api/user', {
headers: authHeader(),
method: 'GET',
})
.then(function(res) {
return res.json();
})
.then(function(data) {
this.setState({ id: data.id });
});
Run Code Online (Sandbox Code Playgroud) 在本地测试服务器 url 上有 ssl 证书错误,所以我必须禁用 ssl 检查。我在stackoverflow上阅读了许多解决方案,但没有一个有帮助。问题是我无法在服务器上进行任何更改。所以我想知道如何禁用 ssl 检查,或者是否有任何其他 api,例如 fetch api 或 Retrofit for react native。?
我的 fetch api 代码如下
fetch('https://example.com/logincheck', {
method: 'post',
headers: {
'Accept': 'application/json, text/plain,',
'Content-Type': 'application/json'
},
body: JSON.stringify({
"username" :"usrname",
})
})
.then(response => response.json())
.then(responseobj => {
this.setState({
});
console.log("login status:",responseobj.success);
})
.catch((error) => {
console.error(error);
});
Run Code Online (Sandbox Code Playgroud) 我有一个 json 文件,我正在尝试读取其内容以在脚本中使用。我使用以下命令来获取 json:
const json = fetch('Data/my_data.json').then(response => response.json());
Run Code Online (Sandbox Code Playgroud)
当我执行此操作并查看控制台中的 json 对象时,我看到它是一个返回的承诺(已解析状态),其中包含文件中的实际 json 对象。但您无法直接访问 PromiseValue。你必须再次使用 then 语句,所以我使用了这个:
json.then(function(getData){metaData = getData;});
Run Code Online (Sandbox Code Playgroud)
metaData 对象未设置为原始 Promise 的值。直到稍后第二个完成时才会取消设置。尽管在最初返回的承诺中该信息已经可用。
是否可以在没有第二个 then 语句的情况下获得原始的承诺值,或者我是否使用第二个 then 语句错误地访问了承诺。
感谢您的任何见解!
我正在尝试使用Fetch API上传大文件,但当我在 chrome 中发布大于 128MB 的数据和在 Firefox 中发布大于 256MB 的数据时遇到了问题。我的问题是无论如何要通过 chrome 或 firefox 中的配置来增加这个最大值?我只是做错了吗?异步发布大数据有更好的选择吗?
这是一个显示问题的简短示例:https : //jsfiddle.net/hspw4bzo
function performFetch() {
const megabytes = document.getElementById( 'megabytes' ).value * 1;
const largeString = (new Array(megabytes * 1024 * 1024 )).join("x");
const options = {
redirect: 'follow',
method: 'POST',
body: largeString
};
fetch( 'https://jsfiddle.net/', options ).then( () => {
console.log( 'success' )
} )
}
Run Code Online (Sandbox Code Playgroud)
当您点击“Go”按钮时,它会启动一个 POST 请求,其主体大小为 128MB。在 chrome 中,这会导致框架崩溃。
我在我的 android 设备上使用 expo 客户端并设置了一个 django 服务器,localhost:8000我正在尝试在 react native 中使用 fetch 访问和端点。我看过如何从我的 Android 设备访问我的本地主机? 你如何在Android模拟器中连接本地主机?以及如何从 Eclipse 中的 Android Emulator 连接到我的 http://localhost Web 服务器,但这不起作用。
我也尝试使用我机器的 ip 地址而不是 localhost,但没有结果。这是一个示例代码
componentDidMount(){
return fetch('http://my-ip-address:8000/restapi/')
.then((response) => {
console.log("success")
response = response.json()
}).catch(error => {
console.error(error)
})
}
Run Code Online (Sandbox Code Playgroud)
我在这里做错了什么?
我正在使用一些承诺来获取一些数据,但我在项目中遇到了这个问题。
example1 = () => new Promise(function(resolve, reject) {
setTimeout(function() {
resolve('foo1');
}, 3000);
});
example2 = () => new Promise(function(resolve, reject) {
setTimeout(function() {
resolve('foo2');
}, 3000);
});
doStuff = () => {
const listExample = ['a','b','c'];
let s = "";
listExample.forEach((item,index) => {
console.log(item);
example1().then(() => {
console.log("First");
s = item;
});
example2().then(() => {
console.log("Second");
});
});
console.log("The End");
};
Run Code Online (Sandbox Code Playgroud)
如果我在代码中调用 doStuff 函数,结果不正确,我预期的结果如下所示。
RESULT EXPECTED
a a
b First
c Second
The End b
First First
Second …Run Code Online (Sandbox Code Playgroud) 我正在使用 chrome devTools 来镜像 webRequest。查看网络请求,响应中有一些我想要访问的 JSON 数据
\n\n右键单击 --> 复制为获取 -->
\n\nfetch(\n "https://www.url.com/service.svc?action=FindConversation&ID=-40&AC=1",\n {\n "credentials":"include",\n "headers":{\n "accept":"*/*",\n "accept-language":"en-US,en;q=0.9",\n "action":"FindConversation",\n "content-type":"application/json; charset=UTF-8",\n "actionid":"-40",\n "unique_identifier":"062lCufCY0i5mI9NMTRUsF87XDq9ttYIonzZQjBcCOPvzoIJFOTSI6ZVNK9lMwy_iPFY2tuZzPY."\n "x-requested-with":"XMLHttpRequest"\n },\n "referrer":"https://ballard.amazon.com/OWA/",\n "referrerPolicy":"no-referrer-when-downgrade",\n "body":"contains some body data I want to manipulate",\n "method":"POST",\n "mode":"cors"\n }\n).then(res => {console.log(res)})\nRun Code Online (Sandbox Code Playgroud)\n\n这会打印出类似这样的内容:
\n\nResponse {type: "basic", url: "https://url/service.svc?action=FindConversation&ID=-40&AC=1", redirected: false, status: 200, ok: true, \xe2\x80\xa6}\nbody: ReadableStream\nlocked: false\n__proto__: ReadableStream\nbodyUsed: false\nheaders: Headers {}\nok: true\nredirected: false\nstatus: 200\nstatusText: "OK"\ntype: "basic"\nurl: "https://url/OWA/service.svc?action=FindConversation&ID=-40&AC=1"\n__proto__: Response\nRun Code Online (Sandbox Code Playgroud)\n\n当我检查刚刚发出的网络请求时,它看起来没有返回任何 JSON 数据,而是用代码进行响应200。这正常吗?
我要么期望它返回 JSON 数据,要么失败。 …
我有一种情况,我需要遍历一组 URL 并获取结果,但我需要保留请求的顺序,即第一个请求应该首先“保存”(写入文件),依此类推. 请求的结果是文本文件,它们的内容没有任何显示原始 URL 或顺序的数据。
我在下面做了一个演示,它获取虚拟的 JSON 数据。
let promises = [];
let data = [];
let i = 1;
let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Accept', 'application/json');
const fn = async() => {
while (i < 5) {
promises.push(
fetch('https://reqres.in/api/users/' + i, {
mode: 'cors',
headers: headers
})
.then(response => response.json())
.then(json => {
data.push(json)
})
)
i++;
}
await Promise.all(promises).then(() => {
console.log(data);
})
}
fn();Run Code Online (Sandbox Code Playgroud)
测试一下上面的代码,可以看到结果是随机排序的(根据id),而且由于我原代码中的文件都是文本文件,所以fetch后无法排序。
fetch-api ×10
javascript ×8
promise ×3
react-native ×2
reactjs ×2
android ×1
asynchronous ×1
cors ×1
django ×1
es6-promise ×1
expo ×1
fetch ×1
react-redux ×1
ssl ×1