标签: fetch-api

没有带fetch()的JSON对象

我设置了oauth。但是,当我想使用fetch()函数获取访问令牌时,它只会返回一个带有_bodyInit,_bodyBlob和标头之类的对象。因此,我只是无法获取JSON对象。无论如何,我都在使用Android。

码:

componentDidMount() {
Linking.getInitialURL().then(url => {
      if(url) {
        console.log(url);
        const queries = url.substring(16)
        const dataurl = qs.parse(queries);
        if(dataurl.state === 'ungessable15156145640!') {
          console.log(dataurl.code);
          console.log(dataurl.state);
          return code = dataurl.code;
        }
      }
    }).then((code) => {
      fetch(`https://dribbble.com/oauth/token`, {
        method: 'POST',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          'client_id': 'MY_ID',
          'client_secret': 'MY_SECRET',
          'code': code
        })
      })
      .then((res) => {
        var access_token = res;
        console.log(access_token);
      });
    });
  }
Run Code Online (Sandbox Code Playgroud)

javascript react-native fetch-api

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

ReactJS componentDidMount和Fetch API

刚开始使用ReactJS和JS,有没有办法将从APIHelper.js获得的JSON返回到App.jsx中的setState dairyList?

我想我不了解React或JS或两者的基本内容.在Facebook React Dev Tools中从未定义dairyList状态.

// App.jsx
export default React.createClass({
  getInitialState: function() {
    return {
      diaryList: []
    };
  },
  componentDidMount() {
    this.setState({
      dairyList: APIHelper.fetchFood('Dairy'), // want this to have the JSON
    })
  },
  render: function() {
   ... 
  }


// APIHelper.js
var helpers = {
  fetchFood: function(category) {
    var url = 'http://api.awesomefoodstore.com/category/' + category

    fetch(url)
    .then(function(response) {
      return response.json()
    })
    .then(function(json) {
      console.log(category, json)
      return json
    })
    .catch(function(error) {
      console.log('error', error)
    })
  }
}

module.exports = helpers;
Run Code Online (Sandbox Code Playgroud)

javascript reactjs fetch-api

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

es6类:在父类中获取,请参阅子类中的已解析获取

假设我有以下数据spanish.json

[
   {"word": "casa", "translation": "house"},
   {"word": "coche", "translation": "car"},
   {"word": "calle", "translation": "street"}
]
Run Code Online (Sandbox Code Playgroud)

我有一个Dictionary类来加载它并添加一个搜索方法:

// Dictionary.js
class Dictionary {
  constructor(url){
    this.url = url;
    this.entries = []; // we’ll fill this with a dictionary
    this.initialize();
  }

  initialize(){
    fetch(this.url)
      .then(response => response.json())
      .then(entries => this.entries = entries)
  }

  find(query){
    return this.entries.filter(entry => 
      entry.word == query)[0].translation
  }
}
Run Code Online (Sandbox Code Playgroud)

我可以实例化它,并使用它通过这个小单页应用程序来查找“ calle”:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>spanish dictionary</title>
</head>
<body>

<p><input placeholder="Search for a Spanish word" type="">  
<p><output></output> …
Run Code Online (Sandbox Code Playgroud)

javascript ecmascript-6 es6-promise fetch-api es6-class

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

提取返回空响应,但“网络”选项卡显示数据

使用以下简单代码段:

fetch("https://www.youtube.com/feeds/videos.xml?channel_id=UCAL3JXZSzSm8AlZyD3nQdBA", { mode: "no-cors" })
  .then(r => {
    console.debug(r);
    r.text().then(t => console.debug(t)).catch(console.error);
  })
  .catch(console.error);
Run Code Online (Sandbox Code Playgroud)

我收到一个空响应(nullbody,empty urlstatus为零,okfalse),但是当我转到“网络”选项卡时,可以在其中的“响应”选项卡中看到数据。我希望fetch回应能给我同样的感觉。

是什么赋予了?我试过添加,credentials: "include"但是没有什么区别,也不应该,没有它就应该可以访问此资源。

javascript fetch-api

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

如何向 javascript 的 fetch() 函数发送额外数据

我想用来fetch()查询支持我的搜索页面的 API 端点。它以 JSON 格式返回搜索结果列表。

我还想将用户提交的当前查询传递给 API。旧的实现使用 jquery 和getJSON。查看 getJSON 的文档,它说我可以传入一个data变量:

数据
类型:普通对象或字符串
随请求发送到服务器的普通对象或字符串。

查看 fetch的文档,我不确定如何将数据作为我的请求的一部分传递。所以我的问题是,我如何传入一个将与我的请求一起发送到服务器的字符串?

编辑:我想我可以将查询附加到请求 URL,如“/search/?q=Something”并发送。有没有人有更好的方法?

javascript jquery json fetch-api

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

使用fetch post请求进行正确的Django CSRF验证

我正在尝试使用JavaScript的fetch库来向我的Django应用程序提交表单.但无论我做什么,它仍然抱怨CSRF验证.

关于Ajax的文档提到了指定我尝试过的头文件.

我还尝试从templatetag中获取令牌并将其添加到表单数据中.

这两种方法似乎都不起作用.

以下是包含表单值和标题的基本代码:

let data = new FormData();
data.append('file', file);;
data.append('fileName', file.name);
// add form input from hidden input elsewhere on the page
data.append('csrfmiddlewaretoken', $('#csrf-helper input[name="csrfmiddlewaretoken"]').attr('value'));
let headers = new Headers();
// add header from cookie
const csrftoken = Cookies.get('csrftoken');
headers.append('X-CSRFToken', csrftoken);
fetch("/upload/", {
    method: 'POST',
    body: data,
    headers: headers,
})
Run Code Online (Sandbox Code Playgroud)

我能够使用JQuery,但想尝试使用fetch.

javascript django django-csrf fetch-api

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

获取 API 默认跨域行为

取规格说的默认获取模式是“无CORS” -

请求具有关联的模式,即“同源”、“cors”、“no-cors”、“导航”或“websocket”。除非另有说明,否则它是“no-cors”。

但是,我似乎注意到了mode: 'no-cors'与未指定模式之间的这种行为差异。如此JSFiddle 示例中所示,将模式显式定义为“no-cors”会使 Javascript 无法访问响应,而未指定模式会使 Response 对象可用于调用方法。

显式指定获取模式的工作方式与内部使用相同模式的默认行为是否不同?我在这里缺少什么?

javascript fetch cors fetch-api

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

在标头中使用令牌获取请求

当我在地址' http:// localhost:8080/clients ' 上执行获取请求时,我需要帮助在标头中包含令牌.

现在我收到此消息"HTTP 403 Forbidden".

授权令牌1234abcd

function getAllClients() {
      const myHeaders = new Headers();
      myHeaders.append('Content-Type', 'application/json');

      return fetch('http://localhost:8080/clients', {
        method: 'GET',
        mode: 'no-cors',
        headers: myHeaders,
      })
        .then(response => response.json())
        .then((user) => {
          console.log(user.name);
          console.log(user.location);
        })
        .catch((error) => {
          console.error(error);
        });
    }

    getAllClients();
Run Code Online (Sandbox Code Playgroud)

javascript fetch fetch-api

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

从服务器获取api获取错误消息,而不是一般消息

我正在使用redux thunk在操作中获取一些数据

function handleErrors(response) {
    console.log(response)
    if (!response.ok) {
        throw Error(response.statusText);
    }
    return response;
}

export const something = (var) => dispatch => {
    fetch(`${url}/something`, {credentials: 'include'})
    .then(handleErrors)
    .then(res => res.json())
    .then(res =>
        dispatch({
            type: SOMETHING,
            payload: res
        })
    )
    .catch(error => 
        dispatch({
            type: ERROR,
            payload: error
        })
    )
Run Code Online (Sandbox Code Playgroud)

我的快递服务器上的错误响应为“某些错误”

return res.status(500).send({ message: 'some error' });
Run Code Online (Sandbox Code Playgroud)

当它获取并且是错误(500)时,其消息是通用的“内部服务器错误”。

如何获取提取中的“某些错误”?

javascript redux fetch-api redux-thunk react-redux

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

导入时,Fetch返回undefined

我有一个从url获取数据的函数,并且应该返回它:

const fetchTableData = () => {
fetch('https://api.myjson.com/bins/15psn9')
    .then(result => result.json())
    .then(data => {
        return data;
    })
}

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

问题是,当我导入此函数并尝试使用它时,它总是返回undefined.

当我控制台记录功能本身内部的数据时,您可以看到它可用.当我尝试导入它时,该功能不起作用.

这里有什么问题?它为什么这样工作?

javascript ecmascript-6 reactjs fetch-api

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