我的服务工作者中有以下代码:
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)
我让我的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)
}
我设法通过使用$ .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是否正确?
我需要将图像文件从react本机应用程序放置到预先配置的s3上传URL中。我看到了一个带有fetch的示例,该示例通过路径将图像上传为二进制文件,但它是作为多部分表单上传进行的。由于s3上传网址只能将其作为主体中的原始二进制文件使用-而不作为多部分的内容类型,因此使用fetch或其他任何其他在本机中运行的库将原始二进制图像作为主体放置成什么语法?
以下代码将其上传为表单数据-这不是我想要的。
var photo = {
uri: response.uri,
name: fileName,
};
const body = new FormData(); // how can I do this not as a form?
body.append('photo', photo);
const results = await fetch('https://somes3uploadurl.com, {
method: 'PUT',
body,
});
Run Code Online (Sandbox Code Playgroud) 我试图点击服务端点,服务是登录服务我使用身份验证类型作为基本,代码是反应和使用获取库但是即使我在我的请求中设置头字段我也无法在网络标签中查看我的请求中相应标头的值?
以下是代码:
var obj = {
method: 'GET' ,
mode : 'no-cors',
headers: {
'Access-Control-Request-Headers': 'Authorization',
'Authorization': 'Basic amFzcGVyYWRtaW46amFzcGVyYWRtaW4=',
'Content-Type': 'application/json',
'Origin': ''
},
credentials: 'include'
};
fetch('http://myreport:8082/jasperserver/rest/login/', obj ).then(…
Run Code Online (Sandbox Code Playgroud)
什么时候process.env.NODE_ENV=='development'- 没关系!
但我们的生产版本在IE 11(11.0.9600)中失败了.铬55都可以正常工作.
devDependencies:
...
babel-core: "6.22.0",
babel-eslint: "^7.0.0",
babel-loader: "^6.2.5",
babel-preset-env: "^1.5.2",
babel-preset-es2015: "^6.16.0",
babel-preset-es2016: "^6.22.0",
babel-preset-es2017: "^6.16.0",
babel-preset-react: "^6.16.0",
babel-preset-stage-0: "^6.22.0"
...
Run Code Online (Sandbox Code Playgroud)
依赖关系:
...
babel-polyfill: "^6.16.0"
...
Run Code Online (Sandbox Code Playgroud)
.babelrc:
{
"presets": [
"react",
["env", {
"useBuiltIns": true
}],
"stage-0"
]
}
Run Code Online (Sandbox Code Playgroud)
尝试"useBuiltIns": false,es2016,es2015,es2017预设.没有什么变化.
index.js:
"use strict";
import 'babel-polyfill'
...
Run Code Online (Sandbox Code Playgroud)
webpack.config module.exports.entry:
vendor: ['babel-polyfill', 'immutable', 'react', 'react-dom', ...],
...
bundle: [path.resolve(__dirname, srcPath + ""index.js)]
Run Code Online (Sandbox Code Playgroud)
vendor是index.html中的第一个脚本.
在控制台中键入_babelPolyfill返回true.但是Headers,fetch是未定义的......
为什么process.env.NODE_ENV=='production'在IE11中破坏我的应用程序?如何修复我的配置?
then(res => res.json())react-native提取中的以下代码段是什么意思?
fetch(url)
.then(res => res.json())
.then(res => {
this.setState({
data: res,
error: res.error || null,
loading: false
});
Run Code Online (Sandbox Code Playgroud)