我使用 fetch 来获取 GET 和 POST 请求的 API 响应。发生错误时,我可以看到状态代码和文本,即 400 Bad Request。但是,还会传递其他信息来解释抛出错误的原因(即用户名不匹配)。我可以通过 Firefox 开发人员工具的控制台在响应有效负载中看到此附加消息,但我不确定如何通过处理获取响应来获取它。
这是一个请求示例:
fetch(url, {
method: 'POST',
body: JSON.stringify({
name: name,
description: description
}),
headers: {
"Content-type": "application/json; charset=UTF-8",
"Authorization": "Bearer " + token
}
}).then(response => {
if (!response.ok) {
throw Error(response.statusText)
}
return response
})
.catch(error => {
console.log(error)
})
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?
fetch我正在React 中执行一个方法,它返回.pdf也已命名的文件,现在我想获取该文件名。
function downloadPdf() {
fetch(BASE_URL + `/example/example/pdf/${exampleId}`)
.then(r => r.blob())
.then(showFile);
}
function showFile(blob, filename) {...}
Run Code Online (Sandbox Code Playgroud)
如何获取文件名并showFile使用文件名调用我的函数?
我正在尝试使用 JS fetch API 发布表单数据,我也成功发送数据并获取响应,但在文件上传中出现错误,我的文件未上传,并且也没有将存储的文件名存储到数据库中。
<form id="signup">
<label for="myName">Send me your name:</label>
<input type="text" id="myName" name="name" value="abc">
<br>
<label for="userId">your id:</label>
<input type="text" id="userId" name="id" value="123">
<br>
<label for="pic">your photo:</label>
<input id="profile" name="profile" id="profile" type="file">
<br>
<input id="postSubmit" type="submit" value="Send Me!">
</form>
Run Code Online (Sandbox Code Playgroud)
和 JavaScript 代码
const thisForm = document.getElementById('signup');
const profile = document.getElementById('profile');
thisForm.addEventListener('submit', async function (e) {
e.preventDefault();
const formData = new FormData(thisForm).entries()
formdata.append("profile",profile.files[0]);
const response = await fetch('<?php echo base_url() . 'api/get_subscription' ?>', {
method: 'POST',
headers: { …Run Code Online (Sandbox Code Playgroud) 我正在使用 WebAssembly 并尝试从 C++ 发出 HTTPS 请求。我看过Emscripten FETCH API的解决方案并尝试使用它。
为了测试它,我创建了一个Test类,在其中发送如下请求:
void Test::sendRequest() {
emscripten_fetch_attr_t attr;
emscripten_fetch_attr_init(&attr);
strcpy(attr.requestMethod, "GET");
attr.attributes = EMSCRIPTEN_FETCH_LOAD_TO_MEMORY;
attr.onsuccess = &Test::onSuccess;
attr.onerror = &Test::onError;
emscripten_fetch(&attr, "http://127.0.0.1:5000/");
}
Run Code Online (Sandbox Code Playgroud)
我的 onSuccess 回调如下所示:
void Test::onSuccess(struct emscripten_fetch_t *fetch) {
printf("Finished downloading %llu bytes from URL %s.\n", fetch->numBytes, fetch->url);
setText(QString::fromUtf8(fetch->data));
emscripten_fetch_close(fetch); // Free data associated with the fetch.
}
Run Code Online (Sandbox Code Playgroud)
但是,当我尝试编译时出现错误:
error: assigning to 'void (*)(struct emscripten_fetch_t *)' from incompatible type 'void
(Test::*)(struct emscripten_fetch_t *)'
attr.onsuccess = &Test::onSuccess;
^~~~~~~~~~~~~~~~ …Run Code Online (Sandbox Code Playgroud) 我在 Postman 中成功请求令牌,但在 React Native 项目中:
{“错误”:“unsupported_grant_type”}
我的代码是从 PostMan 复制的:
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/x-www-form-urlencoded");
var urlencoded = new URLSearchParams();
urlencoded.append("username", "hoanglongit96");
urlencoded.append("password", "admin");
urlencoded.append("grant_type", "password");
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: urlencoded,
redirect: 'follow'
};
fetch("http://192.168.1.38:7777/token", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
Run Code Online (Sandbox Code Playgroud)
结果:
{“错误”:“unsupported_grant_type”}
我尝试在标头中添加Accept: application/json
我正在使用create-react-app和 Laravel开发网络应用程序。create-react-app在 localhost:3000 上运行开发项目,而 laravel 后端在 localhost:8080 上运行。这是我的代码的一部分:
const onSubmit = (e) => {
e.preventDefault();
const val = rootRef(formRef); // React ref to form
// form data
const data = {
firstName: val('firstName'),
lastName: val('lastName'),
facultyId: val('facultyId'),
departmentId: val('departmentId'),
courseNo: val('courseNo'),
phoneNumber: val('phoneNumber'),
emailInput: val('email'),
password: val('password')
}
const request = {
method: "POST",
// mode: "cors",
// cache: "no-cache",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(data)
}
fetch('http://localhost:8080/signup', request)
.then(res => res.json())
.then(console.log)
}
Run Code Online (Sandbox Code Playgroud)
因此,当我提交表单时,我收到419 …
我是 Node.js 和 API 的新手,所以我希望有人能提供帮助!我正在尝试使用 node-fetch 从幻想英超联赛 API 获取 JSON 数据。我已在客户端中成功完成此操作,但从我的 node.js 服务器文件中我不断收到错误:
UnhandledPromiseRejectionWarning:FetchError: https://fantasy.premierleague.com/api/entry/3/处的 json 响应正文无效原因:JSON 输入意外结束
响应本身的状态为 200,但大小为 0,因此它不返回任何数据。我知道它应该可以工作,因为当您访问 url 时 JSON 是清晰可见的,并且我已经可以在客户端代码中使用 fetch 了。
这是我正在使用的代码:
const fetch = require('node-fetch');
async function fetchEntry() {
const api_url = 'https://fantasy.premierleague.com/api/entry/3/';
const fetchEntry_response = await fetch(api_url);
const json = await fetchEntry_response.json();
console.log("json: " + JSON.stringify(json));
};
fetchEntry();
Run Code Online (Sandbox Code Playgroud)
注意:在客户端代码上,我遇到了 CORS 错误,因此需要使用代理(https://thingproxy.freeboard.io/fetch/https://fantasy.premierleague.com/api/entry/3/)让它发挥作用。我不确定这是否相关?
任何帮助将不胜感激!
乔
我想获取一个 URL 并按定义大小的块处理响应。我也不想在等待整个块可用时阻塞。Fetch API 中有类似的功能吗?
示例如下:
const response = await fetch(url)
const reader = response.body.getReader()
const chunk = await reader.read(CHUNK_SIZE)
Run Code Online (Sandbox Code Playgroud) 我的 Chrome 扩展执行了一个 get 请求,效果很好。由于使用代码片段测试速度更快,因此我想在 Chrome 控制台或 Chrome 代码片段中执行完全相同的操作。最小的例子:
fetch(url, {
method: "GET"
}).then(response => response.text())
.then(html => console.log(html))
.catch(error => console.log(error))
Run Code Online (Sandbox Code Playgroud)
不幸的是,我只能得到
TypeError: Failed to fetch对于错误和
Failed to load resource: net::ERR_FAILED在 Chrome 的内联错误标记中
在我的 Chrome 扩展中,我遇到了 CORS 问题,因此我在 AWS Lambda 函数中所做的是将标头设置为
const headers = {
'Content-Type': 'application/json',
"Access-Control-Allow-Headers" : "Content-Type",
"Access-Control-Allow-Origin" : "*",
"Access-Control-Allow-Credentials" : true
};
Run Code Online (Sandbox Code Playgroud)
所以我认为CORS 不是这里的问题。但我似乎无法弄清楚在扩展程序中运行请求与在控制台/代码片段中运行请求会产生什么差异。我在这里可能会缺少什么?
我也没有在 AWS CloudWatch 中看到该请求,所以我想它甚至没有离开我的机器。我正在对安装了 0 个扩展的 Chrome 用户进行测试,在隐身模式下也会发生同样的情况
为了解决我的服务器的任何问题,我还插入了https://lockevn.medium.com/snippet-to-fetch-remote-rest-api-and-display-in-console-of-chrome-devtool中的示例-6896a7cd6041
async function testGet() {
const …Run Code Online (Sandbox Code Playgroud) javascript google-chrome-extension google-chrome-devtools fetch-api
我似乎无法将 javascript 中此 API 调用的值返回到我的 React 组件。我有一个调用 API 的 java 脚本文件。在js文件中,返回结果,但是当我在react组件中调用useEffect中的js函数时,它返回未定义。
export function ordersData() {
const partner_code = localStorage.getItem('partner_code')
let items = []
let data = []
let isLoaded = false
let error = ''
fetch('xxxxxxxxxxxx' + process.env.REACT_API)
.then(res => res.json())
.then((result) => {
for (let instance in result['docs']) {
let payload = (result['docs'][instance])
payload.id = instance
payload.timestamp = shortMonthYear(payload.timestamp)
data.push(payload)
}
items = data.reverse()
}, (err) => {
isLoaded(true)
error(err)
})
}
Run Code Online (Sandbox Code Playgroud)
这是我的矩形组件
导出默认函数 OrdersChart() {
const [payload, setPayload] …Run Code Online (Sandbox Code Playgroud) fetch-api ×10
javascript ×7
reactjs ×3
access-token ×1
asynchronous ×1
c++ ×1
emscripten ×1
fetch ×1
file ×1
filenames ×1
html ×1
laravel ×1
node-fetch ×1
node.js ×1
php ×1
react-native ×1
response ×1
webassembly ×1