所以我这里有这段代码,它从 URL 调用并在控制台中显示数组
fetch('http://jsonplaceholder.typicode.com/users')
.then(
function(response) {
if (response.status !== 200) {
console.log('Looks like there was a problem');
return;
}
response.json().then(function(data){
console.log(data);
});
}
)
.catch(function(err) {
console.log('Fetch Error', err);
})
Run Code Online (Sandbox Code Playgroud)
但是,它打印出:
[object Object] {
address: [object Object] {
city: "Lebsackbury",
geo: [object Object] { ... },
street: "Kattie Turnpike",
suite: "Suite 198",
zipcode: "31428-2261"
},
Run Code Online (Sandbox Code Playgroud)
关于如何删除[object, object]并使其正常显示(与网址中相同)的任何想法?
我正在尝试使用请求的 fetch API 在我的服务器上获取数据,但该请求需要永远处理(它最终会处理)。我使用 React 作为我的视图,Express 为我的页面提供服务。我在下面列出了我的 Express 和 JSX 代码。是否了解为什么会发生这种情况(“已安装”消息按预期立即记录,但 fetch API 在延迟后记录)?
表达:
app.use('/test',function(){
console.log('connected');
})
Run Code Online (Sandbox Code Playgroud)
反应.JS:
componentDidMount(){
console.log('mounted');
fetch('./test').then(function(response){
console.log(response);
}).catch(function(error){
console.log(error);
})
}
Run Code Online (Sandbox Code Playgroud) 我试图将获取函数放入一个单独的文件中,这样我就可以轻松组织这些 API 获取。但是,当我尝试获取并返回数据时,它给我 null 或意外的 json 对象。这是我的 src 的一部分:
//api.js
export async function LoginAPI(username, password) {
const url = baseURL + "/login/";
var params = {username: username, password: md5.hex_md5(password)};
let response = await fetch(url, {
method: 'POST',
headers: {'Accept': 'application/json','Content-Type': 'application/x-www-form-urlencoded'},
body: JSON.stringify(params)
});
return await fetch(url, {
method: 'POST',
headers: header,
body: JSON.stringify(params)
})
.then((res) => res.text())
.then((text) => text.length ? JSON.parse(text) : {})
.catch((error) => {
throw error;
});
};
Run Code Online (Sandbox Code Playgroud)
这是另一个文件。
//index.js
var Login = React.createClass({
onPress_login: function() …Run Code Online (Sandbox Code Playgroud) 我正在使用 fetch 来调用这样的 typescript 文件中的 API,但在浏览器中它会抛出一个错误,指出必须初始化 const configInit,我认为确实如此。知道如何解决这个问题吗?非常感谢
const authHeader = new Headers();
authHeader.append('Authorization', `Bearer ${token}`);
const configInit : RequestInit = {
method: 'GET',
headers: authHeader,
cache: 'default'
};
const configRequest = new Request('/api/econfig', configInit);
Run Code Online (Sandbox Code Playgroud) 我是 React 新手,正在尝试学习它。我正在从 API 获取数据并且我将使用这些数据。它返回基于“美元”的汇率。我将使用该数据来兑换货币,但我收到此错误:此处错误
我不知道问题是什么。
import React, { Component } from 'react';
import './App.css';
class App extends Component {
constructor (props) {
super(props)
this.state = {data: 'false'};
}
componentDidMount(){
this.getData();
}
getData = () => {
fetch("https://openexchangerates.org/api/latest.json?app_id=88a3d2b24b174bf5bec485533a3bca88")
.then(response => {
if (response.ok) {
return response;
} else {
let errorMessage =
'${response.status(${response.statusText})',
error = new Error(errorMessage);
throw(error);
}
})
.then(response => response.json())
.then(json =>{
console.log(json);
this.setState({ data: json.data })
});
}
render() {
return (
<div className="App">
<header …Run Code Online (Sandbox Code Playgroud) 我编写了一个 PHP 脚本,其中返回餐厅名称、地址、电话号码、营业时间表和自定义菜单的链接。但是,即使数据库中有周一的条目,当我在 mysqli_fetch_assoc 中执行 while 循环时,它也不会显示。这是我的代码:
<?php
session_start();
$con=mysqli_connect("root","");
$rest_id2=$_GET['id'];
$rest_id=(int)$rest_id2;
var_dump($rest_id);
$sql="SELECT * FROM restaurant WHERE restaurant_id='".$rest_id."'";
$result=mysqli_query($con,$sql);
$rows=mysqli_fetch_assoc($result);
echo '<strong>'. "Restaurant name:". '</strong><br><br>';
echo $rows['restaurant_name'];
echo "<br><br>";
echo "<strong>Address: </strong><br><br>";
echo $rows['address_1']." ".$rows['address_2']." ". $rows['city']. ", ".
$rows['state']. " ". $rows['zip']. "<br><br>";
echo '<strong>'. "Phone number:". '</strong><br><br>';
echo $rows['phone_number']. "<br><br>";
//hours table
$sql2="SELECT * from hours WHERE restaurant_id='".$rest_id."'";
$result2=mysqli_query($con,$sql2);
$row=mysqli_fetch_assoc($result2);
echo "<table border='1' cellpadding='10'><tr><th>Open or Closed</th> .
<th>Day</th><th>Start Time</th><th>End Time</th></tr>";
$num_rows=mysqli_num_rows($result2);
// var_dump($num_rows);
while($row=mysqli_fetch_assoc($result2)){
// var_dump($rows);
if …Run Code Online (Sandbox Code Playgroud) 我正在尝试在我的 React 应用程序中读取 Json 文件,但控制台显示我的 json 文件的 url 是 404。任何人都可以检查一下我的代码中有什么问题吗
以下是浏览器控制台中显示的错误。当我打开网络选项卡中显示的 json url 时,它会重定向到该页面而不是显示 json -
下面是我的代码 -
-
import React from 'react';
import Header from './Header';
import Container from './Container'
import Footer from './Footer'
class App extends React.Component{
constructor(props) {
super(props);
this.state = {
error: null,
isLoaded: false,
products: []
};
}
componentDidMount() {
fetch("../json/results.json",{
headers : {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
})
.then(res => res.json())
.then(
console.log("--------"),
(result) => {
this.setState({
isLoaded: true,
products: result.Products
});
}, …Run Code Online (Sandbox Code Playgroud) 我正在使用 fetch api 发布数据。在正文中,我发送了employee_id,但我收到来自 Django 的 MulitDictKey 错误,表示未收到它(以及其他数据)。为什么不发送?我缺少什么吗?
\n\n在我的 html 文件中(在 script 标签中):
\n\nconst graduateEmployee = row => {\n const token = row.querySelector(\'INPUT\').value\n fetch(\'/questions/ajax/update_employee\', {\n method: \'POST\',\n headers: {\n "X-CSRFToken": token,\n "Accept": "application/json",\n \'Content-Type\': \'application/json\'\n },\n body:JSON.stringify({\n employee_id: row.id,\n column: \'mentor_status\',\n new_value: false\n })\n }).then((res) => res.json())\n .then((response) => console.log(\'Success:\', JSON.stringify(response)))\n .catch((err)=>console.log(\'Error:\', err))\n }\nRun Code Online (Sandbox Code Playgroud)\n\n在我的views.py中:
\n\ndef update_employee(request):\n employee_id= int(request.POST["employee_id"])\n column = request.POST["column"]\n new_value = request.POST["new_value"]\n employee = Employee.objects.get(employee_id = employee_id)\n employee[column] = new_value\n employee.save()\n return HttpResponse(f\'{column} …Run Code Online (Sandbox Code Playgroud) 长话短说,我将展示代码。
一些.html
<html><script src="some.js"></script></html>
Run Code Online (Sandbox Code Playgroud)
一些.js
window.onload = () => console.log( "onload" );
(async (url, cb) => cb( await ( await fetch(url) ).json() ))
( "some.json", () => console.log( "in async" ) );
Run Code Online (Sandbox Code Playgroud)
和 some.html 输出:
onload
in async
Run Code Online (Sandbox Code Playgroud)
我已经完成了一些工作,例如在实际获取中加载图像,所以fetch().then()对我来说不起作用。
现在我的问题是如标题所示,如何让“onload”等待“fetch”完成?
我正在使用 fetch API 执行照片上传,并且不断收到Type Error Network Request Error. 我在模拟器和设备上收到相同的错误。我使用react-native-image-crop-picker作为照片上传数据的来源。有什么想法吗?
const handlePhotoUpload = async (image: any, token: string) => {
const { path, filename, mime } = image;
const uri = path.replace("file://", "")
const file = {
uri,
type: mime,
name: filename
};
const body = new FormData()
body.append('file', file)
const config = {
method: 'POST',
headers: { 'Authorization': 'Bearer ' + token },
body
};
return await fetch(`${<API URL>}/user/photo`, config)
}
Run Code Online (Sandbox Code Playgroud) fetch ×10
javascript ×6
reactjs ×4
asynchronous ×2
react-native ×2
android ×1
constants ×1
django ×1
express ×1
json ×1
mysql ×1
mysqli ×1
php ×1
python ×1
typescript ×1