标签: fetch

在JS中使用formdata和fetchAPI将表单上传的图片发送到服务器

我正在尝试从单个表单中提取图像和文本数据。我尝试使用 formdata.get('image') 来获取用户选择的图像,但它不起作用,因为我在服务器上收到未定义的值。我想知道使用 formdata 或任何其他方法获取用户在表单中选择的图像的适当方法,谢谢。

表格

 <form id = "register" class = "edit-note" enctype = "multipart/form-data">
                <div>
                    <label>Heading:</label>
                    <input type = "text" name = "heading" placeholder = "<%= Note[0].heading %>" id = "heading">
                </div>
                <div>
                    <label>Small Text:</label>  
                    <input type = "text" name = "stext" placeholder = "<%= Note[0].smallText %>" id = "stext">
                </div>

                <div>
                    <label>Featured Image:</label>
                    <img src = "<%= Note[0].image %>" height = "110px" width = "132px">
                    <input type = "file" name = "image" id = "fimage">
                </div>
                <div> …
Run Code Online (Sandbox Code Playgroud)

javascript forms fetch image-upload

1
推荐指数
1
解决办法
1万
查看次数

为什么发送 fetch() 时我的响应数据未定义?

我正在尝试在客户端使用 fetch() 将数据发送到我的 NodeJS 服务器或从我的 NodeJS 服务器发送数据。

服务器很好地收到了发布请求,并且我能够记录 req 变量,但是当我 res.send('any data') 时,客户端无法检测到数据。奇怪的是,chrome 可以看到响应,但我根本不知道如何引用数据!

客户端代码

fetch('/',{
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
  user:{
    name: 'John',
    email: 'J@B.com',
  }
})
.then(res => console.log(res))
.then(data => console.log(data))
.catch((error) => console.error('Error:',error))
Run Code Online (Sandbox Code Playgroud)

服务器代码

app.post('/', (req,res) => {
  console.log(req.body.user)
  res.send('hello?')
})
Run Code Online (Sandbox Code Playgroud)

Chrome 能够读取响应,但数据字段显示未定义

javascript fetch node.js

1
推荐指数
1
解决办法
6873
查看次数

从 Next.js 应用获取 Strapi API 时,为什么会收到 {statusCode: 400, error: 'Bad Request', message: 'Malicious Path'}

当我尝试从 Strapi API 获取数据时,我从 Next.js 应用程序中获取{statusCode: 400, error: 'Bad Request', message: 'Malicious Path'}. 我的代码如下所示:

import '../styles/globals.css'
import App from "next/app"
import Head from "next/head"
import Link from 'next/link'
import { createContext } from "react";
import { fetchAPI } from "lib/api";
import { getStrapiMedia } from "lib/media"

export const GlobalContext = createContext({})

export default function MyApp({ Component, pageProps }) {
  const { global } = pageProps;
  console.log(global)
  return (
    <>
      <Head>
        <title>{getStrapiMedia(global.siteName)}</title>
        <meta name="viewport" content="initial-scale=1.0, width=device-width" />
        <meta name="description" …
Run Code Online (Sandbox Code Playgroud)

request fetch http-status-code-400 strapi next.js

1
推荐指数
1
解决办法
3110
查看次数

TypeError:.map 不是函数 - React 应用程序

我创建了这个 React 应用程序来练习 fetch API。但是,在编写代码以通过map方法在浏览器上显示数据时,我收到错误消息“TypeError:profile.map不是函数”。下面是代码:

import React, { Fragment, useEffect, useState } from "react";
import "./App.css";

function App() {
  // https://reqres.in/api/users
  const [profile, setProfile] = useState([]);
  const [loading, setLoading] = useState(false);

  const getProfile = async () => {
    setLoading(true);
    const response = await fetch("https://reqres.in/api/users");
    const data = await response.json();
    setProfile(data);
    setLoading(false);
  };

  useEffect(() => {
    getProfile();
  }, []);

  return (
    <Fragment>
      <h1>React fetch</h1>
      <div className="main">
        <section className="section">
          <h2>Get database</h2>
          <div>
            {loading ? (
              <Fragment>loading..</Fragment>
            ) : (
              profile.map(i => { …
Run Code Online (Sandbox Code Playgroud)

crud fetch reactjs fetch-api

1
推荐指数
1
解决办法
3万
查看次数

异步生成器在解决时产生承诺结果

假设我想同时获取 10 个 url,并在收到响应时对其进行处理(其顺序可能与它们在原始列表中出现的顺序不同)。忽略拒绝的可能性,一种方法是简单地为每个 Promise 附加一个“then”回调,然后等待它们全部使用完成Promise.all()

const fetch_promises = [
  fetch("https://cors-demo.glitch.me/allow-cors"),
  fetch("/"),
  fetch("."),
  fetch(""),
  fetch("https://enable-cors.org"),
  fetch("https://html5rocks-cors.s3-website-us-east-1.amazonaws.com/index.html"),
  fetch("https://api.github.com"),
  fetch("https://api.flickr.com/services/rest/"),
];
const processing_promises = [];
for (const fetch_promise of fetch_promises) {
  processing_promises.push(fetch_promise.then(response => {
    // Process response.  In this example, that means just
    // print it.
    console.log("got a response: ",response);
  }));
}
await Promise.all(processing_promises);
Run Code Online (Sandbox Code Playgroud)

切换到输出更清晰、更具确定性的示例:

const sleep = millis => new Promise(resolve=>setTimeout(resolve, millis));
const sleep_promises = [
    sleep(3000).then(()=>"slept 3000"),
    sleep(1000).then(()=>"slept 1000"),
    sleep(5000).then(()=>"slept 5000"),
    sleep(4000).then(()=>"slept 4000"),
    sleep(2000).then(()=>"slept 2000"),
];
const processing_promises …
Run Code Online (Sandbox Code Playgroud)

javascript generator fetch promise async-await

1
推荐指数
1
解决办法
1463
查看次数

Nodejs - 从 url 获取文件并将内容发送到客户端

由于某种原因,我不想公开共享 URL (sercet url),

我的工作流程如下:

客户端向我的服务器发送 API 请求:

API:mywebsite.com/api/image_abc.jpg

我有 Nodejs Express 服务器从 url 获取文件:

例如:sercret_url.com/image_abc.jpg

然后从 Nodejs 的响应图像内容中,我将图像内容发送回客户端并显示为 image_abc.jpg

我在 stackoverflow 上四处查看,但刚刚从磁盘读取文件并发送给客户端得到了答案。我想要的只是将图像内容重定向到客户端,而不是将文件保存到磁盘。

谢谢。

javascript fetch fs node.js express

1
推荐指数
1
解决办法
3503
查看次数

Javascript fetch api 使用自定义错误消息

我正在寻找一种使用本机 javascript fetch api 处理错误的方法。曾经使用 jQuery,但我正在尝试使用更多原生 JavaScript 函数。

我找到了这个博客并喜欢这种方法:https ://learnwithparam.com/blog/how-to-handle-fetch-errors/

fetch(url)
  .then((response) => {
    if (response.status >= 200 && response.status <= 299) {
      return response.json();
    } 

    throw Error(response.statusText);
    
  })
  .then((jsonResponse) => {
    // do whatever you want with the JSON response
  }).catch((error) => {
    // Handle the error
    console.log(error);
  });
Run Code Online (Sandbox Code Playgroud)

然而,在 catch 中我得到了属于 HTTP 代码的 statusText。以400为例Bad request。但这不是我想要的,我对服务器的调用将准确地响应错误。所以我想使用响应正文作为错误。我尝试了不同的方法,但如果 HTTP 代码为 400,我无法获取响应正文。对于 jQuery,我使用了response.responseJSON.html. 但这不适用于 fetch api。

那么我怎样才能使用响应正文作为错误代码。

javascript fetch

1
推荐指数
1
解决办法
6732
查看次数

在 javascript / typescript 中使用“fetch”对 IPFS URI 进行 API 调用(被 cors、网络错误或类型错误阻止)

我有一个在浏览器中运行的 nextjs 打字稿项目,需要发出以下fetch请求:

        const tokenURIResponse = await fetch(
            "ipfs://bafybeig37ioir76s7mg5oobetncojcm3c3hxasyd4rvid4jqhy4gkaheg4/?filename=0-PUG.json"
        )
Run Code Online (Sandbox Code Playgroud)

此调用返回一个 JSON 对象,如下所示:

{
  "name": "PUG",
  "description": "An adorable PUG pup!",
  "image": "https://ipfs.io/ipfs/QmSsYRx3LpDAb1GZQm7zZ1AuHZjfbPkD6J7s9r41xu1mf8?filename=pug.png",
  "attributes": [
    {
      "trait_type": "cuteness",
      "value": 100
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

但是,我不断收到以下错误:

勇敢的:

Unhandled Runtime Error
TypeError: Failed to fetch

Source
components/NFTBox.tsx (85:39) @ _callee$

  83 | 
  84 |         // const tokenURIResponse = await fetch(tokenURI as string)
> 85 |         const tokenURIResponse = await fetch(
     |                                       ^
  86 |             "ipfs://bafybeig37ioir76s7mg5oobetncojcm3c3hxasyd4rvid4jqhy4gkaheg4/?filename=0-PUG.json",
  87 |         )
Run Code Online (Sandbox Code Playgroud)

火狐浏览器:

Unhandled Runtime …
Run Code Online (Sandbox Code Playgroud)

javascript fetch cors typescript ipfs

1
推荐指数
1
解决办法
2067
查看次数

CORS 问题:对预检请求的响应未通过访问控制检查:它没有 HTTP 正常状态

我访问过其他相关帖子,但仍然无法找到解决我的情况的方法......

我正在从站点 A 向站点 B 请求数据。在我的项目中添加了“Access-Control-Allow-Origin”,但现在我收到此错误:“CORS 策略:对预检请求的响应未通过访问控制检查:它没有 HTTP 正常状态”。

附件中你可以看到我的代码:

useEffect(() => {
fetch(
  "https://raw.githubusercontent.com/simoncriado/Wordle/master/data/db.json",
  {
    headers: {
      "Access-Control-Allow-Origin":
        "https://wordle-react-project.netlify.app/",
      "Access-Control-Allow-Methods": [
        "POST",
        "GET",
        "OPTIONS",
        "DELETE",
        "PUT",
      ],
      "Access-Control-Allow-Headers": [
        "append",
        "delete",
        "entries",
        "foreach",
        "get",
        "has",
        "keys",
        "set",
        "values",
        "Authorization",
      ],
    },
  }
)
  .then((res) => res.json())
  .then((json) => {
    const letters = json.letters;
    setLetters(letters);
  });
Run Code Online (Sandbox Code Playgroud)

}, []);

我正在从另一个组件对相同的 URL 进行类似的获取。使用相同的代码。

知道问题出在哪里吗?非常感谢!西蒙

fetch http-headers cors reactjs

1
推荐指数
1
解决办法
3万
查看次数

For 循环不循环 JSON 数组

我从 fetch 中获取了 JSON 格式的运动员姓名列表。使用 for 循环,我想获取花名册 > 运动员 > 姓名下的所有姓名,然后将它们插入到下拉菜单中。

但由于某种原因,循环不起作用。如果我拿出循环并只抓住一名运动员,那就有效了。也许我对数组和对象感到困惑?

JSON代码

{
    "team": {
        "color": "000000",
        "country": "USA",
        "roster": [
            {
                "athlete": {
                    "name": "John Doe",
                    "age": 20
                }
            },
            {
                "athlete": {
                    "name": "Jane Doe",
                    "age": 21
                }
            },
            {
                "athlete": {
                    "name": "Jack Doe",
                    "age": 22
                }
            },
            {
                "athlete": {
                    "name": "Joe Doe",
                    "age": 23
                }
            }
        ]
    }
}
Run Code Online (Sandbox Code Playgroud)

JS代码

async function getAthletes() {

    const getPlayers = document.getElementById('getPlayers')

    await fetch('athlete.json', {
        method: 'GET'
    }) …
Run Code Online (Sandbox Code Playgroud)

javascript arrays json for-loop fetch

1
推荐指数
1
解决办法
66
查看次数