这就是我的目标:
import 'whatwg-fetch';
function fetchVehicle(id) {
return dispatch => {
return dispatch({
type: 'FETCH_VEHICLE',
payload: fetch(`http://swapi.co/api/vehicles/${id}/`)
.then(status)
.then(res => res.json())
.catch(error => {
throw(error);
})
});
};
}
function status(res) {
if (!res.ok) {
return Promise.reject()
}
return res;
}
Run Code Online (Sandbox Code Playgroud)
编辑:承诺不会被拒绝,这就是我想要弄清楚的.
我在Redux中使用这个fetch polyfill和redux-promise-middleware.
谢谢你的光临.
我想送new FormData()的body一个的POST使用请求提取API
操作看起来像这样
var formData = new FormData()
formData.append('myfile', file, 'someFileName.csv')
fetch('https://api.myapp.com',
{
method: 'POST',
headers: {
"Content-Type": "multipart/form-data"
},
body: formData
}
)Run Code Online (Sandbox Code Playgroud)
这里的问题是边界,类似的东西
boundary=----WebKitFormBoundaryyEmKNDsBKjB7QEqu
从来没有进入Content-Type:标题
它看起来应该是这样的
Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryyEmKNDsBKjB7QEqu
当你用a尝试"相同"的操作时new XMLHttpRequest(),就像这样
var request = new XMLHttpRequest()
request.open("POST", "https://api.mything.com")
request.withCredentials = true
request.send(formData)Run Code Online (Sandbox Code Playgroud)
标题已正确设置
Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryyEmKNDsBKjB7QEqu
所以我的问题是,
我如何使这种情况fetch完全像XMLHttpRequest?
如果这不可能,为什么?
谢谢大家!这个社区或多或少是我取得职业成功的原因.
我确信这有一个简单的答案,但对于我的生活,我无法弄清楚如何去做.
我有以下用于上传到Google云端存储的快速端点.它工作得很好,谷歌api的响应给了我一个独特的文件名,我想传回我的前端:
app.post('/upload', (req, res) => {
var form = new formidable.IncomingForm(),
files = [],
fields = [];
form
.on('field', function(field, value) {
fields.push([field, value]);
})
.on('file', function(field, file) {
files.push([field, file]);
})
.on('end', function() {
console.log('-> upload done');
});
form.parse(req, function(err, fields, files){
var filePath = files.file.path;
bucket.upload(filePath, function(err, file, apiResponse){
if (!err){
res.writeHead(200, {'content-type': 'text/plain'});
res.end("Unique File Name:" + file.name);
}else{
res.writeHead(500);
res.end();
}
});
});
return;
});
Run Code Online (Sandbox Code Playgroud)
我通过调用一个将文件传递给它的短函数来到达此端点:
function upload(file) {
var data = new FormData();
data.append('file', …Run Code Online (Sandbox Code Playgroud) 如果我想下载文件,我应该在then下面的块中做什么?
function downloadFile(token, fileId) {
let url = `https://www.googleapis.com/drive/v2/files/${fileId}?alt=media`;
return fetch(url, {
method: 'GET',
headers: {
'Authorization': token
}
}).then(...);
}
Run Code Online (Sandbox Code Playgroud)
请注意,代码位于客户端.
典型的AJAX和Fetch API有什么区别?
考虑这种情况:
function ajaxCall(url) {
return new Promise(function(resolve, reject) {
var req = new XMLHttpRequest();
req.open('GET', url);
req.onload = function() {
if (req.status == 200) {
resolve(req.response);
} else {
reject(Error(req.statusText));
}
};
req.onerror = function() {
reject(Error("Network Error"));
};
req.send();
});
}
ajaxCall('www.testSite').then(x => {
console.log(x)
}) // returns html of site
fetch('www.testSite').then(x => {
console.log(x)
}) // returns object with information about call
Run Code Online (Sandbox Code Playgroud)
这是fetch调用返回的内容:
Response {type: "cors", url: "www.testSite", status: 200, ok: true, statusText: "OK"…} …Run Code Online (Sandbox Code Playgroud) 我有两个应用程序,一个是反应前端,第二个是rails-api应用程序.
我一直很高兴使用isomorphic-fetch,直到我需要将PATCH方法发送到服务器.
我正进入(状态:
Fetch API cannot load http://localhost:3000/api/v1/tasks. Method patch is not allowed by Access-Control-Allow-Methods in preflight response.
Run Code Online (Sandbox Code Playgroud)
但来自服务器的OPTIONS响应包括Access-Control-Allow-Methods列表中的PATCH方法:
这是fetch的实现方式:
const API_URL = 'http://localhost:3000/'
const API_PATH = 'api/v1/'
fetch(API_URL + API_PATH + 'tasks', {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
method: 'patch',
body: JSON.stringify( { task: task } )
})
Run Code Online (Sandbox Code Playgroud)
POST,GET,DELETE设置几乎相同,它们工作正常.
知道这里发生了什么吗?
更新:
方法补丁区分大小写:
https://github.com/github/fetch/blob/master/fetch.js#L200
不确定这是故意还是错误.
更新2
这是预期的,方法类型PATCH需要区分大小写.将行从fetch方法更新为:
method: 'PATCH'
Run Code Online (Sandbox Code Playgroud)
解决了这个问题.
我正在尝试获取文件并返回它的HTML.然而,它并不像我想象的那么简单.
fetch('/path/to/file')
.then(function (response) {
return response.body;
})
.then(function (body) {
console.log(body);
});
Run Code Online (Sandbox Code Playgroud)
这将返回一个名为的对象ReadableByteStream.如何使用它来获取HTML文件内容?
如果我将内容更改/path/to/file为JSON字符串,并将上面的内容更改为:
fetch('/path/to/file')
.then(function (response) {
return response.json();
})
.then(function (json) {
console.log(json);
});
Run Code Online (Sandbox Code Playgroud)
...它正确返回JSON.我该如何获取HTML?
升级到Chrome 64后,我意识到当我在新标签页上加载页面时会出现此错误.
我无法确定它在服务工作者身上的位置.这是我运行fetch的代码:
self.addEventListener('fetch', function(event) {
if (event.request.url.startsWith(self.location.origin)) {
event.respondWith(
caches.match(event.request).then(function(response) {
return response || fetch(event.request).then(function(fetch_resp){
return fetch_resp;
});
})
);
}
});
Run Code Online (Sandbox Code Playgroud)
在这里,对服务工作者有更多了解的人能帮助我解决这个错误吗?
我正在尝试制作一个天气应用程序,显示一周中许多天的天气和温度.我目前正在使用openweathermap api进行此类任务,事情是我想要的信息(即天气的日期)仅以xml格式提供.由于我出于学术原因在ES6(ES2015)中重建它,我想也使用fetch api,但由于fetch方法解析它,它只是传递错误.所以我怎样才能获取它或者mby有更好的方法来实现它.
let apis = {
currentWeather: { //get user selected recomendation weather
api:"http://api.openweathermap.org/data/2.5/forecast/daily?lat=",
parameters: "&mode=xml&units=metric&cnt=6&APPID=/*api key*/",
url: (lat, lon) => {
return apis.currentWeather.api + lat + "&lon=" + lon +
apis.currentWeather.parameters
}
}
};
function getCurrentLoc() {
return new Promise((resolve, reject) => navigator.geolocation
.getCurrentPosition(resolve, reject))
}
function getCurrentCity(location) {
const lat = location.coords.latitude;
const lon = location.coords.longitude;
return fetch(apis.currentWeather.url(lat, lon))
.then(response => response.json())
.then(data => console.log(data))
}
getCurrentLoc()
.then( coords => getCurrentCity(coords))
Run Code Online (Sandbox Code Playgroud) 我想得到一个api,然后再打电话给另一个.在javascript中明智地使用这样的代码吗?
fetch(url, {
method: 'get',
}).then(function(response) {
response.json().then(function(data) {
fetch(anotherUrl).then(function(response) {
return response.json();
}).catch(function() {
console.log("Booo");
});
});
})
.catch(function(error) {
console.log('Request failed', error)
});
Run Code Online (Sandbox Code Playgroud)