我正在开发 AngularJS 1.6 版本。在我的 app.controller.js 中,我添加了三个事件侦听器并附加了一个 deleteStudent 方法。
window.addEventListener('beforeunload', this.deleteStudent, false);
window.addEventListener(
'unload',
() => {
this.deleteStudent
},
false
);
window.addEventListener('pagehide', this.deleteStudent, false);
deleteStudent() {
let Url = "http://localhost:9000/students/3";
const deleteMethod = {
method: 'DELETE',
headers: {
'Content-Type': 'application/json'
},
keepalive: true
};
fetch(Url, deleteMethod);
}
Run Code Online (Sandbox Code Playgroud)
API 调用未到达后端,但在 Chrome 网络选项卡上列为待处理状态。
*上面使用的删除 API 是在 Node js 中创建的,并且与 postman 一起工作正常。
我必须仅在页面卸载时调用此 API,建议使用具有keep-alive属性true的 fetch API 或使用 sendBeacon(),但我的后端 API 是DELETE类型,因此我不能使用 sendBeacon( ),因为它只支持 POST。
我正在尝试访问content-type从我的GET请求返回的内容,以便我可以决定我想要的预览类型(html可能通过 iframe 进行预览,对于 PDF 可能通过某些查看器进行预览)。问题是,当我执行console.log(response.headers)返回的对象时,其中没有内容类型,但是当我检查网络选项卡时,响应标头具有内容类型:html/text。如何从响应标头获取内容类型?这就是我的 GET 请求的样子
const getFile = async () => {
var requestOptions = {
method: "GET",
headers: context.client_header,
redirect: "follow",
};
let statusID = context.currentStatus.ApplicationID;
var response = await fetch(
process.env.REACT_APP_API_ENDPOINT +
"/services/getStatus?ApplicationID=" +
statusID,
requestOptions
);
console.log(response.headers);
if (response.ok) {
let fileHtml = await response.text();
setfileURL(fileHtml);
} else {
alert.show("Someting went wrong");
}
};
Run Code Online (Sandbox Code Playgroud) 希望你今天过得愉快。因此,我使用 Fetch API 将文件上传到服务器,但我还想在后端包含一个 JSON 字符串。但我无法这样做。
现在这就是我的上传文件功能的样子。如果我只想上传文件而不包含 JSON 字符串,则此方法非常有效:
const uploadFile = ( e ) => {
const uploadedFile = e.target.files[ 0 ];
const formData = new FormData();
formData.append( 'data', uploadedFile );
const rawResponse = await fetch( '/upload-file', {
method: 'POST',
body: formData
});
};
uploadFile();
Run Code Online (Sandbox Code Playgroud)
req.files.data使用;在我的 NodeJS 后端获取文件
但是,如果我包含一个 JSON 字符串并尝试上传文件,那么我的 NodeJS 后端会出现未定义的情况。这是 JSON 字符串的样子:
const uploadFile = ( e ) => {
const uploadedFile = e.target.files[ 0 ];
const formData = new FormData();
const str = 'from …Run Code Online (Sandbox Code Playgroud) 在从 API 获取响应的简单 React 应用程序中,以下带有大括号的代码的结果数据值为undefined。
fetch('http://localhost:8000/track/?id='+this.state.input)
.then(res => {res.json()}) //Note Curly braces around {res.json()}
.then((data) => {
console.log(data);
Run Code Online (Sandbox Code Playgroud)
然而,当花括号被删除时,令人惊讶的是它在控制台中获取并打印了响应数据。
fetch('http://localhost:8000/track/?id='+this.state.input)
.then(res => res.json()) //No Curly braces - then works fine
.then((data) => {
console.log(data);
Run Code Online (Sandbox Code Playgroud)
Promise 函数周围有大括号的这种行为的原因是什么?是不是不能使用大括号?为什么?不过 Promise 有点令人困惑。
下面的代码可以在 PHP 中运行,但不能在 JS 中运行。你能告诉我为什么吗?我怎样才能让纯JS版本工作?
async function cccrFlow() {
response = await fetch('assets/club_mems.json');
club_mems = [];
club_mems = await response.json(); // DOESN"T WORK
}
function cccrFlow() {
club_mems = <?php include('assets/club_mems.json');?>; // WORKS PERFECTLY
}
Run Code Online (Sandbox Code Playgroud)
[{"Name":"Ahmedistan, Jamshed","clubEXP":"2022-09-15"},{"Name":"Anaizi, Paul N","clubEXP":"2021-01-27"},{"Name":"Anderson, Simon","clubEXP":"2022-06-30"},{"Name":"Ashes, Bob P","clubEXP":"2022-04-21"}]
Run Code Online (Sandbox Code Playgroud) 很抱歉问这样一个基本问题,Stack Overflow 和 GitHub 上几乎没有相关信息。这一定是愚蠢的事情,但我不明白。
我正在尝试使用 Rocket 0.5 RC1 通过 JavaScript 发送fetch到 Rust post 端点。但我受到以下打击:
POST /api/favorites application/json 没有匹配的路由。
这是完整的日志:
POST /api/favorites application/json:
Matched: (post_favorites) POST /api/favorites
`Form < FavoriteInput >` data guard is forwarding.
Outcome: Forward
No matching routes for POST /api/favorites application/json.
No 404 catcher registered. Using Rocket default.
Response succeeded.
Run Code Online (Sandbox Code Playgroud)
这是我的 main.rs 文件(省略了不相关的部分):
POST /api/favorites application/json:
Matched: (post_favorites) POST /api/favorites
`Form < FavoriteInput >` data guard is forwarding.
Outcome: Forward
No matching routes for POST …Run Code Online (Sandbox Code Playgroud) 我面临的问题是我无法从 NextJS 前端获取现有用户。我使用的后端框架是 Django(以及 django-cors-headers 包)。django-cors-headers 不允许某个 HTTP 请求,但它应该允许。
\n我的 next.config.js 包含重写,以便我可以访问我的后端。
\nasync redirects() {\n return [\n {\n source: \'/api/:path*\',\n destination: \'http://localhost:8000/:path*/\',\n permanent: true,\n },\n ]\n },\nRun Code Online (Sandbox Code Playgroud)\n我的 django-cors-headers 设置如下所示:
\n# CORS\n\nCSRF_TRUSTED_ORIGINS = [\n \'http://localhost:3000\',\n]\n\nCORS_ALLOWED_ORIGINS = [\n \'http://localhost:3000\',\n \'http://localhost:8000\',\n \'http://127.0.0.1:3000\',\n \'http://127.0.0.1:8000\',\n]\n\nCORS_ALLOW_ALL_ORIGINS = True\nRun Code Online (Sandbox Code Playgroud)\n失败的请求尝试获取 ID 为 1 的用户。该用户存在,因此该请求应该成功。
\nfetch(`/api/users/${String(userId)}/`, {\n mode: \'cors\',\n credentials: \'include\',\n headers: {\n \'Content-Type\': \'application/json\',\n },\n })\nRun Code Online (Sandbox Code Playgroud)\n但是,我从请求中得到的唯一结果是有关 CORS 的错误消息。
\nCross-Origin Request Blocked: The Same Origin Policy disallows reading …Run Code Online (Sandbox Code Playgroud) 我在将 blob 附加到 FormData 时遇到了一个奇怪的问题。根据文档(https://developer.mozilla.org/en-US/docs/Web/API/FormData/append),追加函数可以是 String 或 Blob。我的代码是这样的:
const blobFromSync = (...args) =>
import('node-fetch').then(({ blobFromSync }) => blobFromSync(...args));
let file_location = '/path/to/video/file.mp4';
const file = await blobFromSync(file_location);
const chunkSize = 40000;
for (let start = 0; start < file.size; start += chunkSize) {
const chunk = file.slice(start, start + chunkSize + 1)
const form = new FormData();
form.append('file', chunk, 'an-id');
}
Run Code Online (Sandbox Code Playgroud)
控制台记录该块显示它是一个 Blob,但它会抛出此错误:
TypeError: source.on is not a function
at DelayedStream.create (/Users/xxxxxxxxx/Development/terminal-backend/node_modules/delayed-stream/lib/delayed_stream.js:33:10)
at CombinedStream.append (/Users/xxxxxxx/Development/terminal-backend/node_modules/combined-stream/lib/combined_stream.js:45:37)
at FormData.append (/Users/xxxxxxxxx/Development/terminal-backend/node_modules/form-data/lib/form_data.js:75:3) …Run Code Online (Sandbox Code Playgroud) Axios 返回奇怪的垃圾值,例如\n\xef\xbf\xbd2\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbd\xcf\xab\xef\xbf\xbd\xef\xbf\xbdM@\xef\xbf\xbd~\xef\xbf\xbdII\xef\xbf\xbd{!
我在 wsl2 ubuntu 上,节点版本是 v19.0,axios 是 1.2.0
\n我的代码再简单不过了:\n`
\nconst axios = require("axios");\n\naxios.get('https://jsonplaceholder.typicode.com/users')\n .then(response => console.log(response.data))\nRun Code Online (Sandbox Code Playgroud)\nfetch() 工作起来就像一个魅力。有什么想法或可能的解决方案吗?
\n我有一个 vue/vie 项目,在该项目中我试图使用 markdown 将我的 markdown 文件读取到 html 中。
我尝试使用 fetch api 将其作为字符串导入,但只是因为我无法弄清楚如何在 vue 中使用 node.js 代码。
这是 vue 文件:
<script setup>
import { marked } from 'marked'
</script>
<script>
export default {
data() {
return {
query: this.getQueryVariable("q"),
markdown: ''
}
},
mounted() {
fetch('../src/markdown/About.md')
.then(response => response.text())
.then(text => this.markdown = text)
document.querySelector('.marked').innerHTML = marked.parse(this.markdown)
}
}
</script>
<template>
<div class='marked'>
</div>
</template>
Run Code Online (Sandbox Code Playgroud)