如何使用fetchapi javascript(https://github.com/github/fetch)传递查询字符串?
var url = "http://www.abcd.com";
var query = {
a: "test",
b: 2
};
Run Code Online (Sandbox Code Playgroud)
http://www.abcd.com?a=test&b=2当我传递一些参数时,上面应该被转换成fetch
我正在编写一个包装器fetch,我想在发出请求之前向URL添加内容,例如识别查询参数.我无法弄清楚如何Request使用与原始URL不同的URL 制作给定对象的副本.我的代码看起来像:
// My function which tries to modify the URL of the request
function addLangParameter(request) {
const newUrl = request.url + "?lang=" + lang;
return new Request(newUrl, /* not sure what to put here */);
}
// My fetch wrapper
function myFetch(input, init) {
// Normalize the input into a Request object
return Promise.resolve(new Request(input, init))
// Call my modifier function
.then(addLangParameter)
// Make the actual request
.then(request => fetch(request));
}
Run Code Online (Sandbox Code Playgroud)
我尝试将原始请求作为第二个arguent放到Request构造函数中,如下所示:
function …Run Code Online (Sandbox Code Playgroud) 我有一个 Spring REST API,我已经在 Postman 上测试过它,它返回完全有效的 JSON。但是,当我在前端 React 代码上调用相同的 API 时,它会返回 HTML。这是函数,我用来调用 API,
export function run(engine, mediaId, owner, target, access){
let url = engine + "/" + mediaId + "?id=" + owner + "&targetId=" + target + "&access=" + access;
return fetch(full_url, { credentials: "include",
headers: {
"Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
}})
.then((response) => {
return response.json();})
.then((data) => {
console.log(data);
})
.catch((error) => {
console.log(error);
});
}
Run Code Online (Sandbox Code Playgroud)
我在此调用中遇到语法错误Unexpected token < Thus when I check using response.text()我可以看到返回的数据是 HTML 而不是 …
如何将Fetch API返回的任何内容转换为RxJS Observable?是否RxJS.fromPromise帮助吗?
我正在使用来自react-native的Fetch API,并且正在使用打字稿。我的代码如下所示:
let responseLogin = await fetch('http://url_example', {
method: 'POST',
headers: {'Content-Type':'application/json'},
body: requestBody
});
Run Code Online (Sandbox Code Playgroud)
但是我收到以下错误,标题是:
Argument of type '{ method: string; headers: { 'Content-Type': string; }; body: string; }' is not assignable to parameter of type 'RequestInit'.
Types of property 'headers' are incompatible.
Type '{ 'Content-Type': string; }' is not assignable to type 'Headers | string[][]'.
Object literal may only specify known properties, and ''Content-Type'' does not exist in type 'Headers | string[][]'.
Run Code Online (Sandbox Code Playgroud)
我也尝试创建一个自定义标头,但没有任何运气:
let requestHeaders = new Headers(); …Run Code Online (Sandbox Code Playgroud) 我使用 Google Chrome 或 Mozilla Firefox 的本机获取向我的服务器发送查询:
fetch(url, {
method: 'POST',
body: formData,
credentials: 'include'
})
Run Code Online (Sandbox Code Playgroud)
我设置了一个服务器在 3 分钟后发送响应,结果发现两个浏览器只等待 2 分钟。Firefox 在失败之前再次重新发送请求。
有没有办法定义大于 2 分钟的超时(比如无限)?
注意:我不是在寻找任何替代方案.我知道这可以通过XMLHttpRequest来完成.我也不关心浏览器支持.我只想了解新的/即将推出的标准.
我有一个 File对象,我可以使用像这样的fetch上传它:
fetch(url, {
method: "PUT",
body: fileObject,
});
Run Code Online (Sandbox Code Playgroud)
如何从中获取上传进度?
据我所知body,fetch选项可以是ReadableStream.那么也许有一种方法可以将File对象包装到ReadableStream并从中获取进度状态?
例如.这样的事情
fetch(url, {
method: "PUT",
body: asReadableStream(fileObject, onProgress),
});
Run Code Online (Sandbox Code Playgroud)
谢谢.
包.json
{
"type": "module",
"dependencies": {
"@types/node": "^18.6.5",
"typescript": "^4.7.4"
}
}
Run Code Online (Sandbox Code Playgroud)
tsconfig.json
{
"compilerOptions": {
"target": "ES2021",
"module": "ESNext",
"moduleResolution": "node",
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true
}
}
Run Code Online (Sandbox Code Playgroud)
使用节点 v18.7.0,我尝试将从本机 fetch API 返回的网络流转换为节点流。我使用“node:stream”模块中的 Readable.fromWeb 方法。Typescript 返回类型检查错误,但代码使用 @ts-ignore 注释按预期工作。
类型错误
Argument of type 'ReadableStream<Uint8Array>' is not assignable to parameter of type 'ReadableStream<any>'.
Type 'ReadableStream<Uint8Array>' is missing the following properties from type 'ReadableStream<any>': values, [Symbol.asyncIterator]
const nodeStream = Readable.fromWeb(fetchRequest.body)
Run Code Online (Sandbox Code Playgroud)
源代码
Argument of type 'ReadableStream<Uint8Array>' is not assignable to parameter of …Run Code Online (Sandbox Code Playgroud) 当尝试在前端和后端(React Next.js 和 Django)之间使用“fetch”节点函数发出“POST”请求时,我收到“ECONNREFUSED”错误。
使用 Postman 的后端请求按预期工作。
Django 位于端口:8000,Next.js 位于端口:3000。
它一直在工作,直到我安装了 XCode、Ionic 和 Capacitor 包(我真的不知道它们是否是我收到此错误的原因)。
这是错误:
TypeError: fetch failed
at Object.fetch (node:internal/deps/undici/undici:11118:11)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async __WEBPACK_DEFAULT_EXPORT__ (webpack-internal:///(api)/./src/pages/api/account/login.js:18:28)
at async Object.apiResolver (/Users/tomas.leblanc/Dev/HermesApp/frontend/node_modules/next/dist/server/api-utils/node.js:185:9)
at async DevServer.runApi (/Users/tomas.leblanc/Dev/HermesApp/frontend/node_modules/next/dist/server/next-server.js:395:9)
at async Object.fn (/Users/tomas.leblanc/Dev/HermesApp/frontend/node_modules/next/dist/server/base-server.js:496:37)
at async Router.execute (/Users/tomas.leblanc/Dev/HermesApp/frontend/node_modules/next/dist/server/router.js:226:36)
at async DevServer.run (/Users/tomas.leblanc/Dev/HermesApp/frontend/node_modules/next/dist/server/base-server.js:606:29)
at async DevServer.run (/Users/tomas.leblanc/Dev/HermesApp/frontend/node_modules/next/dist/server/dev/next-dev-server.js:450:20)
at async DevServer.handleRequest (/Users/tomas.leblanc/Dev/HermesApp/frontend/node_modules/next/dist/server/base-server.js:321:20) {
cause: Error: connect ECONNREFUSED ::1:8000
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1300:16) {
errno: -61,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '::1',
port: 8000
} …Run Code Online (Sandbox Code Playgroud) 我正在开发一个 Next.js 应用程序,它最初是一个普通的 React 应用程序(使用 create-react-app 创建),我试图将带有 fetch 请求的 cookie 发送到我的服务器。但是,即使我在获取选项中设置了凭据:“包含”,cookie 也不会被发送。
完全相同的代码在“非”Next js 应用程序中工作。
我还添加了“使用客户端”选项。这些文件位于下一版本 13 的新“app”文件夹中。
更新1:这是我使用的一些代码:
async function getToken() {
const res = await fetch(
'http://localhost:8080/api/auth/token', {
credentials: 'include'
}
);
if (!res.ok) {
return null;
}
return res.json();
}
export default async function Component({
children
}) {
const tokenData = getToken();
const token = await tokenData;
/* some other code */
return {
children
}
}Run Code Online (Sandbox Code Playgroud)
更新 2:根据 Edgefish 的输入和进一步的实验,我承认在 Next.js 最高 12 的版本中,可以使用 …
fetch-api ×10
javascript ×5
json ×2
node.js ×2
reactjs ×2
typescript ×2
django ×1
econnrefused ×1
es6-promise ×1
firefox ×1
next.js ×1
node-streams ×1
react-native ×1
rxjs ×1