我期待这个:
fetch('https://response.democratsabroad.org/photos/?tag=alex')
.then(res=>res.json())
.then(res=>console.log(res))
Run Code Online (Sandbox Code Playgroud)
返回一个 json 对象。相反,它返回一个待处理的承诺。
Promise {[[PromiseStatus]]: "pending", [[PromiseValue]]: undefined}
Run Code Online (Sandbox Code Playgroud)
javascript 控制台的屏幕截图 为什么它会传递未解决的承诺而不是已解决的值?
我一直在寻找一种方法来解决这个问题,如果我的搜索技能达不到标准,我深表歉意。
我的问题:我正在获取 API,我想知道所有数据何时已完全加载。通读文档,我似乎可以将 .then 语句与 fetch 链接起来,我认为这会起作用。但是,看起来它们似乎都同时开火,而没有等待前一个 .then 完成。
这是我的代码:
fetch(myUrl, {
method: 'post',
headers: {
'Content-Type': 'application/json; charset=utf-8',
},
credentials: 'include',
body: data
})
.then(fetchStatus)
.then(json)
.then(function(msg){
showSearchResults();
setTimeout(function(){ console.log("Next then should fire after this"); }, 4000);
})
.then(function(){
return console.log("The 2nd is firing!");
});
function fetchStatus(response) {
if (response.status >= 200 && response.status < 300) {
return Promise.resolve(response)
} else {
return Promise.reject(new Error(response.statusText))
}
}
function json(response) {
return response.json()
}
Run Code Online (Sandbox Code Playgroud)
如果是异步的,那就太好了,但这些事件需要同步,因为我正在尝试处理由先前调用 showSearchResults() 创建的内容;
任何帮助深表感谢。
我有一个要读取和写入的 JSON 文件,如下所示:
[
"test@example.com"
]
Run Code Online (Sandbox Code Playgroud)
我想使用fetch()API向此文件添加信息。到目前为止,我只能从这个文件中读取。
let handle = JSON.stringify(`test@example2.com`); // handle is fine irrelevant of "" or ``
const url = `../json/emails.json`; // URL is fine
const options = {
method: `POST`, // PUT return error at second fetch: SyntaxError: "JSON.parse: unexpected character at line 1 column 1 of the JSON data"
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: handle
};
fetch(url) // this fetch is fine
.then(response => {
if (!response.ok) {
throw new …Run Code Online (Sandbox Code Playgroud) 我不知道为什么它不起作用。它返回空$_POST。
JS:
const updateRequest = new FormData();
updateRequest.append('updateRequest', 'next-period');
fetch('file.php', {
method: 'POST',
data: updateRequest
})
.then((response) => response.text())
.then((text) => {
console.log(text);
})
Run Code Online (Sandbox Code Playgroud)
PHP:
<?php
if($_SERVER['REQUEST_METHOD'] === 'POST') {
var_dump(empty($_POST));
}
Run Code Online (Sandbox Code Playgroud)
在 PHP 文件中,服务器请求是 POST 但 var_dump 记录为 true。
我正在尝试在我的 javascript 代码中使用 fetch 调用一些 API。我正在我的机器上使用 ReactJs 进行开发,并在同一网络中进行另一项开发,在另一台机器上使用 .net 开发 API。使用邮递员,我可以调用 API,但不能使用 fetch。我尝试在其他服务器中调用另一个 API,结果成功。
我正在使用 fetch 并尝试使用 axios。我在堆栈溢出的其他问题中发现了这个 API:https : //gturnquist-quoters.cfapps.io/api/random。答案说尝试获取它们,我尝试但再次抛出相同的错误。
我获取 gturnquist API 的代码:
const myHeader = new Headers();
myHeader.append('Content-Type', 'application/json');
fetch('http://gturnquist-quoters.cfapps.io/api/random', {
method: 'GET', headers: myHeader,
})
.then((res) => {
console.log(res);
return {};
})
.then(res => console.log(res));
Run Code Online (Sandbox Code Playgroud)
和我的代码来获取我需要的 API:
const myHeader = new Headers();
const token = 'mytoken';
myHeader.append('id-tenant', token);
myHeader.append('Content-Type', 'application/json');
const id = 'myid';
const url = 'myurl';
fetch(`http://10.1.1.35/${url}/${id}`, {
method: 'GET',
headers: myHeader, …Run Code Online (Sandbox Code Playgroud) 我们正在对 React-Native 应用程序(使用 Jest)进行单元测试,该应用程序使用fetch.
fetch为了测试它们,我们模拟了 API 调用函数中的调用。到目前为止效果很好。我们还有组合这些 API 调用并对其进行一些逻辑操作的函数。
例如,下面是一个函数,给定令牌后,该函数将获取相关用户的第一个项目 ( project[0]) 并返回该项目中的项目列表。
export async function getAllItems(token) {\n try {\n const response = await getCurrentUser(token); // fetch called inside\n const responseJson = await response.json();\n const allItemsResp = await getAllItemsFromSpecificProject(\n token,\n responseJson.projectIds[0],\n ); // fetch called inside\n return await allItemsResp.json();\n } catch (error) {\n console.log(error);\n return null;\n }\n}\nRun Code Online (Sandbox Code Playgroud)\n函数getCurrentUser和getAllItemsFromSpecificProject都是简单的fetch调用,目前已正确模拟。这是一个尝试测试该getAllItems功能的测试:
it('Gets all items', async () …Run Code Online (Sandbox Code Playgroud) 我正在获取 github 的 api 来显示我的项目。我有标题、描述、链接,但我不知道是否有可能从 readme.md 或其他地方获取图像?我需要它显示在标题和描述旁边。在 github repo 中,我将其放在 src/images/image_1 等目录中。
为什么会fetchData多次触发?在console.log似乎环几乎是无限?如何让它在加载时仅运行一次并在fetchData()稍后调用时仅触发一次?我在这里做错了什么或错过了什么?
const [data, setData] = useState(null);
let fetchData = React.useCallback(async () => {
const result = await fetch(`api/data/get`);
const body = await result.json();
setData(body);
console.log(data)
},[data])
useEffect(() => {
fetchData();
},[fetchData]);
Run Code Online (Sandbox Code Playgroud)
更新(附加问题):如何在下面data的之前等待填充return()现在给出错误,因为它最初为空?:data.map is not a function
return (
<select>
{data.map((value, index) => {
return <option key={index}>{value}</option>
})}
</select>
)
Run Code Online (Sandbox Code Playgroud) 我四处寻找,但似乎找不到有效的答案。我正在遵循 Dennis Ivy 的电子商务网站 Django 教程,但遇到了一个问题,我试图将商品添加到购物车但没有任何反应,检查控制台时出现以下两个错误:
POST http://127.0.0.1:8000/update_item/ 500(内部服务器错误)
updateUserOrder @ cart.js:26 (获取行)
(匿名)@ cart.js:15(调用函数时)
127.0.0.1/:1 未捕获(承诺中)语法错误:JSON 中位置 0 处出现意外标记 <
omise.then(异步)
updateUserOrder @ cart.js:39 (第二个 .then)
(匿名)@ cart.js:15(调用函数时)
这是我的 JavaScript cart.js updateUserOrder 函数:
function updateUserOrder(productId, action) {
console.log('User is logged in, sending data...')
var url = '/update_item/'
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': csrftoken,
},
body: JSON.stringify({ 'productId': productId, 'action': action })
})
.then((response) => {
return response.json()
})
.then((data) => {
location.reload()
});
}
Run Code Online (Sandbox Code Playgroud)
这是我的观点 …
我有一个关于fetch在 html 文件中使用的简单问题。
我在 AWS Api Gateway 中创建了一个 API,它有一个简单的 GET 方法:GET 方法返回一个 json。
现在,如果我直接访问或使用邮递员访问我的方法的链接,它可以正常工作,但是当我尝试使用fetch错误时,我看不到任何结果。
我在互联网上搜索,因为我既不知道 javascript 也不知道 html,但我找不到如何使它正常工作。例如,我在下面的代码中尝试做的是将通过 GET 获取的 json 放入标签中。
这是我的 html 文件:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>test.html</title>
</head>
<body>
<dl>
<dt>Page 1</dt>
<dd>Go to <a href="https://xxx.execute-api.eu-central-
1.amazonaws.com/prod/getcustomerdetailsbyemail/">link</a></dd>
</dl>
<p> <input name="Button" value="Click me" onclick="buttonClick()" type="button"> <input
name="Button2" value="Click me 2" formmethod="get" onclick="buttonClick2()" type="button">
</p>
<p> <input id="myText" name="Message" value="Insert text" type="text"></p>
<label for="myText" id="mylabel"></label>
<div id="myData"> </div>
<dl> …Run Code Online (Sandbox Code Playgroud) fetch-api ×10
javascript ×10
json ×2
promise ×2
reactjs ×2
django ×1
ecmascript-6 ×1
github-api ×1
html ×1
jestjs ×1
php ×1
react-native ×1
use-effect ×1
use-state ×1