从ReactJS-Redux前端应用程序,我尝试获取REST API响应的Location Header值。
当我卷曲时:
curl -i -X POST -H "Authorization: Bearer MYTOKEN" https://url.company.com/api/v1.0/tasks/
Run Code Online (Sandbox Code Playgroud)
我有这个答案:
HTTP/1.1 202 ACCEPTED
Server: nginx
Date: Fri, 12 Aug 2016 15:55:47 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 0
Connection: keep-alive
Location: https://url.company.com/api/v1.0/tasks/status/idstatus
Run Code Online (Sandbox Code Playgroud)
当我在ReactJS中进行抓取时
var url = 'https://url.company.com/api/v1.0/tasks/'
fetch(url, {
method: 'post',
credentials: 'omit',
headers: {
'Authorization': `Bearer ${token}`
}
}
)
Run Code Online (Sandbox Code Playgroud)
我在响应对象中没有任何标头: Fetch请求中没有标头
我尝试了在https://developer.mozilla.org/zh-CN/docs/Web/API/Headers中找到的所有response.headers函数:
response.headers.get('Location');
Run Code Online (Sandbox Code Playgroud)
但是,由于标题为空,因此结果为空。
您知道为什么我无法获得包含标题值的正确Header对象吗?
所以我有这个Picker组件,对于这些项目,我从服务器获取数据并在状态更改时映射它.
//api.js
var api = {
getBooks() {
var url = 'http://192.168.43.14:8080/api/books/'
var headers = new Headers();
headers.append('Accept', 'application/json');
return fetch(url, headers)
.then((res) => res.json())
.catch(function(err) {
console.log('Fetch Error :-S', err);
throw Error(err);
});
}
}
//RegisterMobile.js
import api from '../utilities/api'
export default class RegisterMobile extends Component {
constructor(props) {
super(props)
this.state = {
books: [],
book: '',
mobile: '',
displayError: false,
error: 'Please provide a valid mobile number'
}
}
componentWillMount() {
api.getBooks().then((res) => {
this.setState({
books: res
}) …Run Code Online (Sandbox Code Playgroud) 我在项目中使用Fetch(Fetch API),为了保持一致,我想创建一个接收所有参数(如方法,url和数据)的函数,并创建正确的请求,具体取决于它是GET还是POST请求.
是否有可能使用Fetch发送一个数据对象,该数据对象用于GET请求,将数据转换为参数,并且如果它是POST请求,它只是在正文中发送数据对象?
它看起来像这样:
fetch ('/test', {
method: 'GET',
data: {
test: 'test'
}
});
Run Code Online (Sandbox Code Playgroud)
这个疑问的灵感来自于这个jQuery ajax行为:
$.ajax({
url: '/test',
method: 'GET',
data: {
test: 'test'
}
});
Run Code Online (Sandbox Code Playgroud)
这会产生这个请求:
'/test/?test=test'
Run Code Online (Sandbox Code Playgroud) 这是我的样品请求:
var header = new Headers({
'Platform-Version': 1,
'App-Version': 1,
'Platform': 'FrontEnd'
});
var myInit = {
method : 'GET',
headers: header,
mode : 'no-cors',
cache : 'default'
}
fetch('http://localhost:3000/api/front_end/v1/login', myInit)
.then(res => {
console.log(res.text())
})
Run Code Online (Sandbox Code Playgroud)
当我调试时,我看到此请求已成功发送到服务器,但服务器尚未收到标头参数(在本例中为Platform-Version,App-Version和Platform).请告诉我哪个部分配置错误.
谢谢
我正在调用API来使用fetch API从服务器下载excel文件,但它没有强制浏览器下载,下面是我的标题响应:
HTTP/1.1 200 OK Content-Length: 168667
Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
Server: Microsoft-IIS/8.5
Content-Disposition: attachment; filename=test.xlsx
Access-Control-Allow-Origin: http://localhost:9000
Access-Control-Allow-Credentials: true
Access-Control-Request-Method: POST,GET,PUT,DELETE,OPTIONS
Access-Control-Allow-Headers: X-Requested-With,Accept,Content-Type,Origin
Persistent-Auth: true
X-Powered-By: ASP.NET
Date: Wed, 24 May 2017 20:18:04 GMT
Run Code Online (Sandbox Code Playgroud)
在我用来调用API的代码下面:
this.httpClient.fetch(url, {
method: 'POST',
body: JSON.stringify(object),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
})
Run Code Online (Sandbox Code Playgroud) 所以我一直在构建一个使用Fetch API发出请求的应用程序.不幸的是,我认为Facebook文档中显示的代码(可能是?)不正确.
问题
启动应用程序时,Fetch会调用URL来提取JSON数据.
componentDidMount(){
return fetch(REQUEST_URL)
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,
data: JSON.stringify(responseJson)
})
})
.catch((error) => {
console.error(error);
});
}
Run Code Online (Sandbox Code Playgroud)
这类似于Facebook文档提供的代码.
问题是,当我启动应用程序时,数据不会在渲染功能中呈现.
render() {
if (this.state.isLoading) {
return (
<View style={{flex: 1, paddingTop: 20}}>
<ActivityIndicator />
</View>
);
}
var data = this.state.data;
return this.renderData(data);
}
Run Code Online (Sandbox Code Playgroud)
至少,直到我点击/触摸屏幕后才会渲染.触摸屏幕后,数据呈现.否则,它只会处于永久的"加载"状态.
解?
我记得在过去的某个时候,我不得不将事件处理程序绑定到各自的控件(例如,this.handleClick = this.handleClick.bind(this))
这让我想到:承诺请求中的这个在哪里?这指向哪里?
componentDidMount(){
return fetch(REQUEST_URL)
.then((response) => response.json())
.then((responseJson) => {
this.setState({ <--- **Where are you going?**
isLoading: …Run Code Online (Sandbox Code Playgroud) XHR responseType='document'非常棒,因为它可以为您提供一个可以使用querySelector等的DOM文档:
var xhr = new XMLHttpRequest();
xhr.open('GET', '/', true);
xhr.responseType = 'document';
xhr.onload = function(e) {
var document = e.target.response;
var h2headings = document.querySelectorAll('h2');
// ...
};
Run Code Online (Sandbox Code Playgroud)
这种fetch方法有可能吗?
我有来自我的服务器的响应buildings : [record1, record2, ...],我想只得到该响应的数组.我怎样才能从Promise获得数组?我尝试了一些异步/等待的东西,但我不明白如何在这段代码中使用它:
setupImpagination() {
....
fetch(pageOffset, pageSize, stats) {
return fetch(`http://localhost:3000/api/building/all?skip=${pageOffset}&limit=${pageSize}`)
.then(response => {
console.log('response.json() => ',response.json());
response.json()
})
.catch((error) => {
console.error(error);
});
}
});
}
Run Code Online (Sandbox Code Playgroud) 使用javascript提取并调用rest服务,如果成功,则该服务返回blob,否则返回错误消息json。如何在提取中进行处理?实际的服务是asp.net Web API实现,成功时将返回FileStreamResult(或FileContentResult),否则返回带有json且包含错误消息的错误代码。以下是我要执行的操作的示例:
fetch('flowers.jpg').then(function(response) {
if(response.ok) {
return response.blob();
} else {
return response.json();
}
}).then(function(myBlob) { // here I would also like to function(jsonError)
var objectURL = URL.createObjectURL(myBlob);
myImage.src = objectURL;
}).catch(function(error) {
console.log('There has been a problem with your fetch operation: ', error.message);
});
Run Code Online (Sandbox Code Playgroud) javascript es6-promise fetch-api asp.net-core asp.net-core-webapi
我正在使用JavaScript编写一个小程序。基本上,我想使用Promise和fetch从两个文本文件中提取文本。但是,我不知道如何从文件中获取实际的文本。这是我当前的代码。
sample.txt
this is
a sample
text file.
Run Code Online (Sandbox Code Playgroud)
sample2.txt
this is
the second
sample file.
Run Code Online (Sandbox Code Playgroud)
index.js
function getSampleText() {
Promise.all([
fetch('sample.txt'),
fetch('sample2.txt')
]).then(allResp => {
let sampleResp = allResp[0];
let sample2Resp = allResp[1];
console.log(sampleResp);
console.log(sample2Resp);
})
}
Run Code Online (Sandbox Code Playgroud)
这是应许...我该如何从中得到建议?
fetch-api ×10
javascript ×7
react-native ×3
es6-promise ×2
promise ×2
ajax ×1
asp.net-core ×1
async-await ×1
asynchronous ×1
aurelia ×1
download ×1
http-headers ×1