我已经创建了一个页面,我想通过API调用从数据库中获取所有数据,但是我对VueJS和Javascript也很陌生,我也不知道我在哪里弄错了。我确实使用Postman进行了测试,并且获得了正确的JSON。
这是我得到的:
[__ob__: Observer]
length: 0
__ob__: Observer {value: Array(0), dep: Dep, vmCount: 0}
__proto__: Array
Run Code Online (Sandbox Code Playgroud)
这就是我要的:
(140) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, …Run Code Online (Sandbox Code Playgroud) 我目前正在构建一个带有 React 前端的 Ruby on Rails Webpacker 应用程序。我现在想要创建调用 Rails API 所需的所有请求。我大致遵循本教程https://www.youtube.com/watch?v=0bKc_ch6MZY(https://github.com/daryanka/react-query-tutorial/blob/master/src/containers/Post.js,https://github.com/daryanka/react-query-tutorial/blob/master/src/Queries.js),为了编写一些基于 axios 的查询函数,我可以将其与react-query一起使用。当端点的 url 是硬编码字符串时,我可以毫无问题地让查询按预期运行。当我尝试传入一个参数来创建动态网址时,我遇到了无法访问该参数的问题;特别是“prodId”参数。然而,我确实注意到“prodId”位于“key”参数数组内,如下所示:
queryKey: Array(2)
0: "product"
1: "1"
length: 2
enter code here
Run Code Online (Sandbox Code Playgroud)
我可以从那里访问它,但这种方法似乎有点不对劲,我也没有找到任何尝试从查询键数组访问参数的示例或文档。我想知道我在传递参数方面做错了什么?反应查询中是否有一些我没有考虑到的语法变化?
反应查询@^3.17.2
webpacker (5.2.1)
axios@^0.21.1
//Product.js
import axios from "axios"
import { getProduct } from "../../queries/products"
import { useQuery } from "react-query"
const prodId= '1'
const { data } = useQuery(['product', prodId], getProduct)
//queries/products.js
import axios from 'axios'
export const getProduct = async (key, { prodId }) => { …Run Code Online (Sandbox Code Playgroud) 尝试使timeoutaxios 工作的方法时遇到问题。
为了测试:我故意设置了一个错误的 API 端点:它接受请求,抛出错误(例如:)throw new Error(\xe2\x80\x9ctesting for timeout\xe2\x80\x9d)并且故意不执行任何其他操作。
一旦我调用测试 API 端点,我的客户端应用程序 (reactJS) 就会挂起 - 我预计它会在 2 秒内超时(我设置的超时)。我可以验证该应用程序正在与服务器建立联系。只有当我终止测试 API 服务器时,我的客户端应用程序才会立即继续。
\n示例代码:
\nconst axios = require(\'axios\')\n\nconst test1Press = async () => {\n try\n {\n await axios.post(\'https://mynodeserver.com/api/debug/throw\', {timeout: 2000})\n console.log("post call passed")\n }\n catch (err)\n {\n console.log("post call failed")\n }\n}\nRun Code Online (Sandbox Code Playgroud)\n编辑(~2020):
\n经过进一步研究,看起来 axiostimeout仅适用于响应超时,而不适用于连接超时。针对连接超时的建议解决方案是取消方法(例如signal、cancelToken (deprecated)):
对此进行了测试并工作:
\nconst …Run Code Online (Sandbox Code Playgroud) 我需要从Google Maps API链接一些API请求,而我正在尝试使用Axios.
这是第一个请求,它位于componentWillMount()中
axios.get('https://maps.googleapis.com/maps/api/geocode/json?&address=' + this.props.p1)
.then(response => this.setState({ p1Location: response.data })) }
Run Code Online (Sandbox Code Playgroud)
这是第二个请求:
axios.get('https://maps.googleapis.com/maps/api/geocode/json?&address=' + this.props.p2)
.then(response => this.setState({ p2Location: response.data }))
Run Code Online (Sandbox Code Playgroud)
然后我们有第三个请求,这取决于前两个完成:
axios.get('https://maps.googleapis.com/maps/api/directions/json?origin=place_id:' + this.state.p1Location.results.place_id + '&destination=place_id:' + this.state.p2Location.results.place_id + '&key=' + 'API-KEY-HIDDEN')
.then(response => this.setState({ route: response.data }))
Run Code Online (Sandbox Code Playgroud)
如何将这三个调用链接起来,以便第三个调用在前两个调用之后发生?
我试图从返回这个的 API 中呈现一个简单的用户列表:
[{"UserID":2,"FirstName":"User2"},{"UserID":1,"FirstName":"User1"}]
Run Code Online (Sandbox Code Playgroud)
我不完全理解如何处理带有类型的 Axios 响应。打字稿错误是
Type '{} | { id: number; firstName: string; }' is not assignable to type 'IntrinsicAttributes & UserListProps & { children?: ReactNode; }'.
Property 'items' is missing in type '{}' but required in type 'UserListProps'.
Run Code Online (Sandbox Code Playgroud)
来自下面文件中的<UserList />元素Users.tsx。我的User界面有问题吗?
import React, {useEffect, useState, Fragment } from 'react';
import UserList from './UserList';
import axios, {AxiosResponse} from 'axios';
interface User {
id: number;
firstName: string;
}
const Users: React.FC = (props) => …Run Code Online (Sandbox Code Playgroud) 我正在尝试在 Jest 官方文档中执行模拟模块示例: https: //jestjs.io/docs/mock-functions
test('should fetch users', () => {
const users = [{name: 'Bob'}];
const resp = {data: users};
axios.get.mockResolvedValue(resp);
return Users.all().then(data => expect(data).toEqual(users));
});
Run Code Online (Sandbox Code Playgroud)
但是mockResolvedValue给了我这个打字稿错误:
类型“<T = any, R = AxiosResponse>(url: string, config?: AxiosRequestConfig | undefined) => Promise”上不存在属性“mockResolvedValue”。ts(2339)
我的开发依赖:
"devDependencies": {
"@babel/cli": "7.13.0",
"@babel/core": "7.12.17",
"@babel/plugin-proposal-class-properties": "7.12.13",
"@babel/preset-env": "7.12.17",
"@babel/preset-react": "7.12.13",
"@babel/preset-typescript": "7.12.17",
"@jest/reporters": "26.6.2",
"@types/axios": "0.14.0",
"@types/jest": "26.0.20",
"@types/luxon": "1.26.2",
"@types/node": "14.14.35",
"@types/react": "17.0.3",
"@types/react-dom": "17.0.2",
"@types/react-redux": "7.1.16",
"@types/react-router": "5.1.12",
"@types/react-router-dom": "5.1.7",
"@types/redux-actions": "2.6.1", …Run Code Online (Sandbox Code Playgroud) 有人可以解释为什么返回Axios承诺允许进一步链接,但应用then()/catch()方法后返回不?
例:
const url = 'https://58f58f38c9deb71200ceece2.mockapi.io/Mapss'
function createRequest1() {
const request = axios.get(url)
request
.then(result => console.log('(1) Inside result:', result))
.catch(error => console.error('(1) Inside error:', error))
return request
}
function createRequest2() {
const request = axios.get(url)
return request
.then(result => console.log('(2) Inside result:', result))
.catch(error => console.error('(2) Inside error:', error))
}
createRequest1()
.then(result => console.log('(1) Outside result:', result))
.catch(error => console.error('(1) Outside error:', error))
createRequest2()
.then(result => console.log('(2) Outside result:', result))
.catch(error => console.error('(2) Outside error:', error))Run Code Online (Sandbox Code Playgroud)
<script …Run Code Online (Sandbox Code Playgroud)如何从异步函数返回值?我试着喜欢这个
const axios = require('axios');
async function getData() {
const data = await axios.get('https://jsonplaceholder.typicode.com/posts');
return data;
}
console.log(getData());
Run Code Online (Sandbox Code Playgroud)
它给我这个,
Promise { <pending> }
Run Code Online (Sandbox Code Playgroud) 所以我有这个代码:
axios({
method: 'post',
url,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
data: {
json,
type,
}
})
Run Code Online (Sandbox Code Playgroud)
最初我有正常axios.post但我改变了这个,因为我认为它可能是一个标题问题.但是我仍然没有检测,我$_REQUEST也没有$_POST.但是,它正在接收数据file_get_contents("php://input").
知道什么是错的吗?
编辑
好吧,我想我知道什么是错的.它将它作为json对象发布,因此只能在php://输入中读取.如何在axios中将其更改为普通字符串?
我正在下载带有axios的 zip 文件。为了进一步处理,我需要获取已下载的“原始”数据。据我所知,在 Javascript 中有两种类型:Blob 和 Arraybuffers。两者都可以responseType在请求选项中指定。
在下一步中,需要解压缩 zip 文件。我为此尝试了两个库:js-zip 和 adm-zip。两者都希望数据是一个 ArrayBuffer。到目前为止一切顺利,我可以将 blob 转换为缓冲区。在此转换之后,adm-zip 总是很高兴地提取 zip 文件。但是,js-zip 会抱怨文件损坏,除非 zip 已'arraybuffer'作为 axios下载responseType。js-zip 不适buffer用于从blob.
这让我很困惑。我想这两个ArrayBuffer和Blob本质上的底层内存只是意见。将某些内容下载为 blob 与缓冲区之间可能存在性能差异。但是结果数据应该是一样的吧?
好吧,我决定进行实验并发现:
如果指定responseType: 'blob',axios 会将 转换response.data为字符串。假设您对该字符串进行哈希处理并获得哈希码 A。然后将其转换为缓冲区。对于这种转换,您需要指定一种编码。根据编码的不同,您将获得各种新的哈希值,我们称它们为 B1、B2、B3,...当指定 'utf8' 作为编码时,我将返回原始哈希值 A。
所以我猜当下载数据为 a 时'blob',axios 隐式地将其转换为用 utf8 编码的字符串。这似乎非常合理。
现在您指定responseType: 'arraybuffer'. Axios 为您提供了一个缓冲区作为response.data. 对缓冲区进行哈希处理,您会得到一个哈希码 C。此代码与 A、B1、B2 中的任何代码都不对应,...
那么当下载数据为 时'arraybuffer',你得到完全不同的数据? …
axios ×10
javascript ×6
reactjs ×6
node.js ×2
typescript ×2
arraybuffer ×1
arrays ×1
async-await ×1
asynchronous ×1
blob ×1
jestjs ×1
laravel ×1
php ×1
promise ×1
react-native ×1
react-query ×1
vue.js ×1
webpacker ×1