我的服务工作者中有以下代码:
self.addEventListener('fetch', function (event) {
var fetchPromise = fetch(event.request);
fetchPromise.then(function () {
// do something here
});
event.respondWith(fetchPromise);
});
Run Code Online (Sandbox Code Playgroud)
但是,它在开发控制台中做了一些奇怪的事情,似乎是使脚本异步加载而不是同步(在这种情况下是坏的).
有没有办法在没有fetch(event.request)手动调用的情况下完成请求?
例如:
// This doesn't work
self.addEventListener('fetch', function (event) {
event.request.then(function () {
// do something here
});
});
Run Code Online (Sandbox Code Playgroud) 我对如何正确使用fetch感到困惑.即使我收到错误状态,它似乎也解决了.以下代码是否正确(将获取包装在另一个承诺中)?
function a(url, config) {
if (!config)
config = {};
config = Object.assign(config, {
headers: {
'content-type': 'application/json;charset=utf-8'
}
})
return new Promise(
function(resolve, reject) {
fetch(url, config).then(
function(res) {
if (res.status == 200 && res.ok) {
console.log("Promise resolved")
resolve(res);
return;
}
console.log("Promise rejected")
reject(res);
},
function(rej) {
console.log("promise rejected")
reject(rej);
}
)
}
)
}
function b() {
a('/test').then(
function(res) {
console.log('success');
console.log(res)
},
function(rej) {
console.log('Rejected');
console.log(rej)
}
)
}
b();Run Code Online (Sandbox Code Playgroud)
我正在使用javascript fetch API使用以下代码查询跨域api:
fetch('https://api.com/search?query="2016"').then(function (response) {
console.log(response.headers.get('Access-Control-Allow-Headers'))
console.log(response.headers.get('Content-Range'))
console.log(response.headers.get('Accept-Range'))
console.log(response.headers.get('Date'))
console.log(response.headers.get('Content-Type'))
})
Run Code Online (Sandbox Code Playgroud)
响应标头如下:
Accept-Range:cars 300
Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:Origin, X-Requested-With, Content-Type, Accept, Content-Range, Accept-Range
Access-Control-Allow-Methods:PUT, POST, OPTIONS, GET
Access-Control-Allow-Origin:*
Cache-Control:no-cache
Connection:keep-alive
Content-Range:0-99/1941
Content-Type:application/json
Date:Tue, 12 Jan 2016 12:17:55 GMT
Transfer-Encoding:chunked
Run Code Online (Sandbox Code Playgroud)
非常奇怪的是,只有"Content-Type"适用于其他我得到null:
null
null
null
null
application/json
Run Code Online (Sandbox Code Playgroud)
我需要做什么来检索那些空标题?
我在我的应用程序中使用Fetch Api.
我有一个PHP服务器页面来获取之前已经定义的会话数据.看起来像这样:
<?php
header('Content-Type: application/json; charset=UTF-8');
header('Access-Control-Allow-Origin: *');
session_start();
// $_SESSION['data'] already defined before
$result = array();
// print_r($_SESSION['data']);
if (isset($_SESSION['data'])) {
$result = $_SESSION['data'];
$result['code'] = 'ok';
} else {
$result['code'] = 'error';
}
echo json_encode($result, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
Run Code Online (Sandbox Code Playgroud)
我还有另一个html页面来获取会话数据.看起来像这样:
<script>
$(function() {
// use $.ajax
$.ajax({
url: 'session.php',
dataType: 'json'
})
.done(function(res) {
console.log(res);
});
// end
// use fetch
fetch('session.php').then(function(res) {
if (res.ok) {
res.json().then(function(obj) {
console.log(obj);
});
}
});
// end
});
</script>
Run Code Online (Sandbox Code Playgroud)
问题是,当我使用$ .ajax()时,可以正确显示会话数据.但是当我使用fetch()时,会话数据是未定义的.
那么,出了什么问题,我该如何解决?谢谢!
我让我的React客户端将带有fetch api的文件发布到'/ dataset'端点.
import 'whatwg-fetch';
uploadData(csv) {
this.dataset = csv;
fetch('/dataset', {
method: 'POST',
body: this._fileToFormData(csv)
}).then(
(response) => {
console.log(response);
}
).catch( () => {} );
};
_fileToFormData(file) {
var formData = new FormData();
formData.append('file', file);
return formData
};
Run Code Online (Sandbox Code Playgroud)
我的Flask服务器应该拿起它.
@app.route('/dataset', methods=['POST'])
def dataset():
print request.get_data()
csv_data = request.form['file']
print csv_data
return '{ "fake_json":100}', 200
Run Code Online (Sandbox Code Playgroud)
但是,该csv_data对象只是一个unicode字符串,'[object File]'
代码
print "form:", request.form
print "files:", request.files
Run Code Online (Sandbox Code Playgroud)
回报
ImmutableMultiDict([('file', u'[object File]')])
ImmutableMultiDict([])
Run Code Online (Sandbox Code Playgroud)
如何获取CSV文件的实际内容?
===编辑:解决===
变量csv实际上是一个单独的文件数组,所以我需要提取出来的文件.
我正在为我的反应原生应用程序制作登录页面.当我的用户名和密码有效且无效时,我的api会发送不同的响应.所以我想在一些状态变量中跟踪并保存我的响应状态,然后相应地执行功能.请建议我这样做的方法.
doSignUp() {
console.log("inside post api");
fetch('MyApiUrl', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
password: this.state.password,
email:this.state.email,
name: this.state.firstname,
last_name :this.state.last_name,
mobile:this.state.mobile,
ssn:"2222222"
})
}).then((response) => {console.log('response:',response.status);
response.json()}
.then((responseData) => {
console.log("inside responsejson");
console.log('response object:',responseData)
console.log('refresh token:',responseData[0].token.refresh_token)
console.log('access token:',responseData[0].token.access_token);
}).done();
Run Code Online (Sandbox Code Playgroud)
}
所以我想使用fetch API,这很好,但是用它做的所有请求都属于Google Chrome中的"其他"部分.我更喜欢那些在XHR部分.
这是http.js我用于这些请求的服务.
import 'whatwg-fetch'
import Auth from './Auth';
import Url from 'url-parse';
const API_URL = process.env.API_URL
const http = {
get: get,
getAuthed: getAuthed,
post: post,
postAuthed: postAuthed,
getDefaultHeaders: getDefaultHeaders,
getApiUrl: getApiUrl,
}
window.http = http
export default http
function post(url, data, extraHeaders, opts) {
extraHeaders = extraHeaders || {}
opts = opts || {}
let request = performRequest(url, {
method: 'POST',
headers: mergeHeaders(getDefaultHeaders(), extraHeaders),
body: JSON.stringify(data),
})
if (opts.returnRawRequest) {
return request
} …Run Code Online (Sandbox Code Playgroud) 我设法通过使用$ .getJSON从闪烁提要api获取json响应,但是当我尝试使用Fetch时,我似乎只获得了XML响应.
这有效:
var flickerAPI = "http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";
$.getJSON(flickerAPI, {
tags: "searchTerm",
tagmode: "any",
format: "json"
})
.done(function (data) {
//....
});
Run Code Online (Sandbox Code Playgroud)
这不起作用:
var flickerAPI = "http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";
var request = new Request(flickerAPI, {
mode: 'no-cors',
tags: 'searchTerm',
tagmode: 'any',
format: 'json'
});
fetch(request)
.then(function (res) {
return res.json();
})
.then(function (text) {
console.log(text);
});
Run Code Online (Sandbox Code Playgroud)
我还想了解为什么在使用Fetch API时我得到:"请求资源上没有'Access-Control-Allow-Origin'标头.因此不允许原点'null'访问.如果提供不透明的响应您的需求,将请求的模式设置为'no-cors'以获取禁用CORS的资源." 并且当使用$ .getJSON时没有.谢谢 !!
Chrome版本:57.0.2987
实际上,在较旧的Chrome版本中我也有这个问题.我Authorization在Request Header上添加了访问令牌,
fetch('https://example.com/endpoint', {
method: 'GET',
headers: {
'Authorization': 'Bearer ' + accesstoken
}
})
Run Code Online (Sandbox Code Playgroud)
我总是在Chrome中Access-Control-Allow-Headers:authorization使用响应标题除此之外,我的提取始终是请求方法:选项(不显示GET),然后Status Code在Chrome中为200 OK
但是如果我在Firefox(版本52.0.1)中运行相同的获取代码,一切都很好.我可以添加Authorization在请求标题正确.它不会显示Access-Control-Allow-Headers:authorization在响应头在Firefox.它将显示Authorization: Bearer accesstoken在Request标头上.
服务器端已经为我的请求标头处理了CORS ..
这是Chrome错误或我的代码错误?我应该怎么做才能让Authorization在请求头在Chrome是否正确?
我正在尝试获得我似乎无法正常工作的在线游戏API的请求。我使用的是Fetch API,有些请求需要使用Authorization Bearer令牌,但是该请求永远不会与授权标头一起发送。
我试过了
mode: 'no-cors',
credentials: 'include'
Run Code Online (Sandbox Code Playgroud)
显然将Authorization放在标题中
header: { 'Authorization': 'Bearer TOKEN' }
Run Code Online (Sandbox Code Playgroud)
但该请求仍不符合授权。谁能指出我正确的方向?
编辑这是我提出要求的方式
fetch(URL, {
credentials: 'include',
header: {
'Authorization': 'Bearer TOKEN'
}
})
Run Code Online (Sandbox Code Playgroud)