标签: fetch-api

如何像 jQuery 一样使用 fetch() 来 POST 数据?

我正在尝试从某些代码中删除 jQuery。我只将它用于 POST 操作,因此我想删除它并使用 fetch() 代替。但我无法使用相同的数据让 fetch() 工作。php文件工作正常,只是没有接收到数据

这将为以下两个测试用例设置测试数据:

var toPostObj = new(Object);
toPostObj.action = "update+file";
toPostObj.arrays = [["2020-12-28", "23:20:56", "Trying from ztest", "9.jpg"]];
Run Code Online (Sandbox Code Playgroud)

这可以使用 jQuery 来实现:

$.post('toMariaDB.php', {  // url
    data: toPostObj 
}, function(data2, status, jqXHR) {
    console.log ("data2",data2);
});
Run Code Online (Sandbox Code Playgroud)

使用 fetch() 不起作用:

fetch("toMariaDB.php", { 
    method: "POST", 
    body: toPostObj,   // using JSON.stringify(toPostObj) also doesn't work 
    headers: { "Content-type": "application/text; charset=UTF-8" } 
}) 
.then(response => response.text()) 
.then(text => console.log(text))//; 
.catch(error => {
    console.error(error)
})
Run Code Online (Sandbox Code Playgroud)

出于调试目的,toMariaDB.php 会写出它接收到的数据以及来自 toMariaDB 的任何其他消息的日志文件。
运行 jQuery …

javascript php jquery fetch-api

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

如何使用 Fetch API 发布身体数据?

下面是在邮递员中导入并运行后成功返回响应的curl命令。

    curl --request POST \
--data "grant_type=password" \
--data "username=test" \
--data "password=xyz1234" \
--data "scope=write" \
--data "client_id=test" \
--data "client_secret=test12" \
"https://example.com/access_token"
Run Code Online (Sandbox Code Playgroud)

下面是我如何在 js 代码中使用 fetch api 发送数据。

       const response = await fetch ('https://example.com/access_token', 

  {
    'credentials' : 'include',
     method: 'POST',
     headers: {
      'Content-Type': 'application/json',
      },
     body: JSON.stringify({ grant_type:'password',username:'test',password:'xyz1234',scope:'write',client_id:'test',client_secret:'test12'}),
})
Run Code Online (Sandbox Code Playgroud)

然而,从 Chrome 开发者工具复制后生成的等效卷曲如下。

curl --request POST \
--data-raw '{"grant_type":"password","username":"test","password":"xyz1234","scope":"write","client_id":"test","client_secret":"test12"}'
"https://example.com/access_token"
Run Code Online (Sandbox Code Playgroud)

我怀疑正文数据的格式不正确。这可能会导致 400 错误代码响应。我应该如何使用 fetch api 等价于工作curl 命令发送数据?

javascript json postman fetch-api

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

在 Chrome 扩展 (V3) 中使用 fetch() 时,使用 declarativeNetRequest 设置“Referer”标头

我正在使用清单 V3 开发 chrome 扩展。该扩展的核心功能是使用户能够将数据从网站发送到我的 django 应用程序的 REST API,其中用户已经登录。在本地测试时一切都很好,但是当我去登台测试时,我发现使用 HTTPS django 需要在 POST 标头中使用“referer”来进行 CSRF 保护。

据我发现,chrome 扩展只是不附加该标头。所以我declarativeNetRequest使用以下代码尝试了 API。然而,这仅当我在选项卡中打开 URL 时才有效。当调用 fetch 来发布到相同的 URL 时,规则不匹配。这是在 V3 中使用 fetch 时强制引用标头的正确方法吗?谢谢!

清单.json:

...

"permissions": [
    ...
    "declarativeNetRequestWithHostAccess",
    "declarativeNetRequestFeedback"
  ],
  "declarative_net_request": {
    "rule_resources": [{
      "id": "ruleset_1",
      "enabled": true,
      "path": "rules.json"
    }]
  },

...
Run Code Online (Sandbox Code Playgroud)

规则.json:

[
  {
    "id": 1,
    "priority": 1,
    "action": {
      "type": "modifyHeaders",
      "requestHeaders": [
        {
          "header": "Referer",
          "operation": "set",
          "value": "whatever"
        }
      ]
    },
    "condition": {
      "urlFilter": "https://api.myserver.com",
      "resourceTypes": …
Run Code Online (Sandbox Code Playgroud)

google-chrome-extension django-rest-framework fetch-api

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

NextJS 13 部署时无法从内部 api 路由获取

当从 npm run dev 或 npm run build/start 中的 /api 获取时,我的代码正在工作,但是当尝试将其部署在 Vercel 上时,它无法获取。我将 Next js 13 与应用程序目录一起使用。

这是我在客户端(服务器组件)上的代码

const getAvailableSlots = async () => {
  const res = await fetch(
    `${process.env.NEXT_PUBLIC_API_URL}/api/availabilityList`
  );
  if (!res.ok) {
    console.log(res);
  }

  return res.json();
};

const Appointments = async () => {
  const data = await getAvailableSlots();
  return (
    <div className="App">
      <div>
        <AppointmentsPage data={data} />
      </div>
    </div>
  );
};

export default Appointments;
Run Code Online (Sandbox Code Playgroud)

这是 /api 路线:

const handler = async (req, res) => {
  await connectDB(); …
Run Code Online (Sandbox Code Playgroud)

mongodb server fetch-api next.js next.js13

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

为什么React在使用map函数时不渲染任何东西?

我想返回并渲染<li>包含所获取商店标题的元素,但只有<li>组件中的项目符号显示,没有内容。

import { useEffect, useState } from "react";

export default function Home() {
    const [stores, setStores] = new useState(null);
    const [error, setError] = new useState(null);
    const [isLoading, setIsLoading] = new useState(true);

    useEffect(() => {
        const getStores = async () => {
            try {
                const response = await fetch("https://www.cheapshark.com/api/1.0/stores");
                if (!response.ok) throw new Error(`Error: ${response.status}`);

                let data = await response.json();
                console.log(data);
                setStores(data);
                setError(null);
            }
            catch(err) {
                setError(err.message);
                setStores(null);
            }
            finally {
                setIsLoading(false);
            }  
        }
        
        getStores()
    }, []); …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs fetch-api

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

为什么我不能在 Request 对象上设置一些标头?

我正在尝试请求一个需要使用令牌进行身份验证的 REST API。构造 Request 对象时,一些标头会消失。为什么我无法设置授权标头?

let http_headers = {
        "Content-type": "application/json",
        'Authorization': 'Token token='+my_token,
        'Accept': 'Application/json'
    };

let url = this.base_url + '/api/v1/test';
let init =  {
            method: "POST",
            headers: new Headers(http_headers),
            mode: 'no-cors',
            credentials: 'omit' // I try that, but it doesn't seem to have effect
        };
let req = new Request( url, init );
console.log(req.headers.get("Accept")); // Application/json
console.log(req.headers.get("Authorization")); // null, why ?
Run Code Online (Sandbox Code Playgroud)

javascript request-headers fetch-api

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

如何在 javascript fetch() 方法上传递带 url 的变量?

我正在尝试使用 javascript 上的 GET 方法从 URL 获取数据,

fetch('/api/staffattendance/{makedate}')
  .then(res => res.json())
  .then(res => {
    //this.staffs = res.data;
    console.log(res.data);
  })
  .catch(err => console.log(err));
Run Code Online (Sandbox Code Playgroud)

我如何在这里传递变量:

fetch('/api/staffattendance/{makedate}')
Run Code Online (Sandbox Code Playgroud)

像这样

在此输入图像描述

提前致谢,

javascript fetch-api

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