标签: fetch

使用工作箱时如何从缓存的 url 中忽略 url 查询字符串?

有没有办法使用工作箱从下面的注册路由中忽略查询字符串“?screenSize=”!如果我可以使用正则表达式,我将如何在下面的场景中编写它?基本上,无论 screenSize 查询字符串是什么,我都希望匹配缓存。

workboxSW.router.registerRoute('https://example.com/data/image?screenSize=980',
workboxSW.strategies.cacheFirst({
    cacheName: 'mycache',
    cacheExpiration: {
        maxEntries: 50
    },
    cacheableResponse: {statuses: [0, 200]}
})
);
Run Code Online (Sandbox Code Playgroud)

尝试 cachedResponseWillBeUsed 插件后:我没有看到应用了该插件: 在此处输入图片说明

caching fetch service-worker progressive-web-apps workbox

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

如何使用 fetch 保存 JWT 响应头?

我正在使用 React 并使用 fetch 向服务器发送请求:

fetch("http://localhost:8001/api/login", {
    method: 'post',
    headers: {
        "Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
    },
    body: 'username=' + this.state.username + '&password=' + this.state.password
})
.then(function (response) {
    console.log('Request succeeded with JSON response', data);
    console.log(data.headers.toString())
})
.catch(function (error) {
    console.log('Request failed', error);
});
Run Code Online (Sandbox Code Playgroud)

这是 chrome 检查,它显示我从服务器获取 JWT 令牌 我的问题是如何在我的代码中访问它?我实际上需要将它保存到一个变量中,真的没有办法

data.headers.jwt
Run Code Online (Sandbox Code Playgroud)

如果这没有意义,我很抱歉,如果您需要,我可以澄清。

javascript fetch http-headers reactjs

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

在反应样板中实现 axios 拦截器的最佳方式是什么?

我正在使用使用 fetch 库的 react 样板。但是现在我想实现拦截器,有没有人知道如何使用 fetch 库来实现它,或者我应该为此使用 axios。

fetch reactjs react-native axios react-boilerplate

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

为什么我在本地 node.js/express 服务器的响应中没有得到 JSON 对象?

-- 情况背景 --

我正在为我们的商业营销策略服务的客户进行电子表格注册等等...

表格已经完成,看起来很棒。现在我需要将它连接到我们的业务用来保存/排序/查询/等提交信息的服务的现有 API。

我是一名初级开发人员,API 非常复杂。我只想确保我的 ES6/javascript 处于正常工作状态。ajax 调用正在工作,我的代码中没有错误等。因此,为了测试事物,似乎最简单的方法就是制作一个简单的本地服务器,这样我就可以测试我的调用使一切正常工作,然后再开始处理大量API 文档并将其正确连接到我们的服务。第一个电话似乎工作正常。但是我无法让我的小宝贝服务器正确地“响应”一些静态信息来解析。我主要是前端开发人员,但我现在很痴迷于解决这个小服务器问题......所以非常感谢帮助。

-- 获取请求 --

fetch('http://localhost:4000/send-zip')
            .then( 
                (response) => {
                    response.json(),
                    console.log('begin fetch to local server'),
                    console.log(response),
                    populate_store_selector(response)
                })
            .catch(
                (error)=> console.log('basic fetch request failed' + error)
            )
Run Code Online (Sandbox Code Playgroud)

-- 其他功能,以防人们问-

(它只是为了迭代并填充一个 html 输入 type="select" )

function populate_store_selector(arg) {
    for (i of arg) {
        let new_option = document.createElement('option')
        new_option.innerHTML = arg[i]
        select_shop.appendChild(new_option)
    }
}
Run Code Online (Sandbox Code Playgroud)

-- 我的小宝贝服务器 --

const express = require('express')
const server = express()

server.use(function (req, res, next) {
    res.header("Access-Control-Allow-Origin", …
Run Code Online (Sandbox Code Playgroud)

javascript ajax fetch node.js express

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

使用 javascript fetch() 获取 md 文件的问题

我目前正在开发一个网络应用程序,其中大部分内容都是用 Markdown 编写的。因此,为了处理这个问题,我想我可以创建一个 github 存储库来托管所有降价文件,然后使用 fetch() api 从 github 中获取文件。

我的代码看起来像这样:

fetch('https://github.com/erasabi/trekthroughs/blob/master/pen_testing/RickdiculouslyEasy.md')
    .then(response => response.blob())
    .then(result => console.log(result));
Run Code Online (Sandbox Code Playgroud)

但是当我这样做时,我收到了这个错误:

无法加载https://github.com/erasabi/trekthroughs/blob/master/pen_testing/RickdiculouslyEasy.md:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,不允许访问 Origin 'null'。如果不透明响应满足您的需求,请将请求的模式设置为“no-cors”以在禁用 CORS 的情况下获取资源。

无论如何要这样做吗?最终结果是,一旦我获取了降价文件的内容,我想使用 showdown 或markedjs 将内容转换为网站的 html。

javascript markdown github fetch

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

如何使用 then() 将 Fetch 响应的 JSON 主体传递给 Throw Error()?

编辑:你误解了。考虑这个伪代码。这基本上是我想要做的,但是当这样写时它不起作用。

使用 Fetch 收到 Laravel 422 响应后,将response不包含实际的 JSON 数据。您必须使用response => response.json()才能访问它。我已经放了一张照片,response我还提供了使用后的输出response => response.json()

不想将对象转换为 JSON 字符串。

我在 Laravel 中使用 SweetAlert2。

throw error(response => response.json())

swal({
  title: 'Are you sure you want to add this resource?',
  type: 'warning',
  showCancelButton: true,
  confirmButtonText: 'Submit',
  showLoaderOnConfirm: true,
  allowOutsideClick: () => !swal.isLoading(),
  preConfirm: () => {
    return fetch("/resource/add", {
        method: "POST",
        body: JSON.stringify(data),
        credentials: "same-origin",
        headers: new Headers({
          'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
          'Content-Type': 'application/json',
          'Accept': 'application/json' …
Run Code Online (Sandbox Code Playgroud)

javascript fetch laravel sweetalert2

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

如何使用 Fetch API POST 数据和参数,例如在 Axios 中

以下面的 Axios 为例:

axios.post(this.reportURL, reportData, {
  params: {
    param1: paramValue1,
    param2: paramValue2
  },
});
Run Code Online (Sandbox Code Playgroud)

如何使用 fetch API 做同样的事情?我看到参数是这样完成的:

fetch(this.reportURL, {
  method: "POST",
  body: "param1=paramValue1&param2=paramValue2",
  headers: 
    {
      "Content-Type": "application/x-www-form-urlencoded"
    }

})
Run Code Online (Sandbox Code Playgroud)

由于 body 键用于存储参数,我是否需要序列化我的整个 reportData 对象并将其连接到现有参数?

我不明白为什么 Fetch API 使用 body 键作为参数。

此外,这不是我自己的 API,我无法更改预期的 POST 请求。

javascript fetch axios

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

setState 在 axios fetch 中不起作用

class ItemsPage extends React.Component {

  constructor(props)
  {
    super(props)
    this.state = {items: null }
    this.fetchImages = this.fetchImages.bind(this)
  }


  fetchImages()
  {
    var self = this

    axios.get('https://api.instagram.com/v1/users/self/media/recent/?access_token=')
      .then(function (result)  {
        const items = result
        self.setState({ items: 'test' })
      });

  }

  componentDidMount()
  {
    this.fetchImages()
    console.log(this.state.items)
  }

  render () {

    return (

      <div>Test</div>


    );

  }
}
Run Code Online (Sandbox Code Playgroud)

我定itemsnullconsole.lognull仍然出现在我试着登录的结果,我得到我的数据Im寻求帮助,请!也试过在es6中使用箭头函数还是不行setState

javascript fetch nodes reactjs axios

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

如何创建可在 Reactjs 中重用的 API utils

我是 ReactJS 的初学者,我正在尝试改进我的代码编写,我最终进入了 API 调用部分,我想提高我的 API 调用的可重用性并将它们设置为特定的文件夹像 utils / APIcalls.js 但我不知道最好的方法和正确的方法来做到这一点,我有以下 API 调用 getItems():

主页.jsx

export default class Home extends Component {
    constructor(props) {
        super(props);
        this.state = {
            'items': [],
            isLoading: false,
            error: null,
        };
    }

    componentDidMount() {
        this.getItems()
        this.refresh = setInterval(() => this.getItems(), 100000);
    }

    componentWillUnmount() {
        clearInterval(this.refresh)
    }

    getItems() {
        this.setState({ 'isLoading': true });
        fetch('https://xxx/api/article/')
            .then(results => {
                if (results.ok) {
                    return results.json();
                } else {
                    throw new Error('Something went wrong ...');
                }
            })
            .then(results => this.setState({ 'items': …
Run Code Online (Sandbox Code Playgroud)

javascript api fetch reactjs

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

在 foreach 循环中获取多个链接

我有一系列像这样的链接:

let array = ['https://1','https://2','https://3']
Run Code Online (Sandbox Code Playgroud)

比我想循环所有元素并在它们上运行 fetch 。仍然 fetch 是异步的,所以我多次收到请求我处理这个问题,从数组中删除元素,如下所示:

array.forEach((link,index) => {
    fetch(link, {mode: 'no-cors'}).then(function () {
        //more stuff not inportant
    }).catch(e => {
        console.error('error', e);
    });
    array.splice(index,1)
})
Run Code Online (Sandbox Code Playgroud)

我想知道有没有更好的解决方案来解决这个问题?

javascript asynchronous fetch

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