Javascript 从Axios API返回数据
我正在尝试使用Node.JS应用程序发出和接收API请求。它使用Axios向另一台服务器发出get请求,并从它接收的API调用中接收数据。第二个代码段是脚本从调用返回数据的时间。它实际上会将其写入控制台,但不会在第二个API中将其发送回Javascript 从Axios API返回数据,javascript,node.js,rest,axios,Javascript,Node.js,Rest,Axios,我正在尝试使用Node.JS应用程序发出和接收API请求。它使用Axios向另一台服务器发出get请求,并从它接收的API调用中接收数据。第二个代码段是脚本从调用返回数据的时间。它实际上会将其写入控制台,但不会在第二个API中将其发送回 function axiosTest() { axios.get(url) .then(function (response) { console.log(response.data); /
function axiosTest() {
axios.get(url)
.then(function (response) {
console.log(response.data);
// I need this data here ^^
return response.data;
})
.catch(function (error) {
console.log(error);
});
}
我知道这是错误的,我只是想找到一种方法让它发挥作用。我似乎只能通过console.log从中获取数据,这对我的情况没有帮助。问题是原始的
axiosTest()
函数没有返回承诺。为了清晰起见,这里有一个扩展的解释:
函数axiosTest(){
//为axios请求创建承诺
const promise=axios.get(url)
//然后,创建一个提取数据的新承诺
const dataPromise=promise.then((response)=>response.data)
//还它
返回数据承诺
}
//现在我们可以从外部使用这些数据了!
轴突
。然后(数据=>{
json({message:'Request received!',data})
})
.catch(err=>console.log(err))
可以更简洁地编写函数:
函数axiosTest(){
返回axios.get(url).then(response=>response.data)
}
或使用异步/等待:
异步函数axiosTest(){
const response=wait axios.get(url)
返回响应.data
}
axiosTest()
正在异步启动,且未被等待
随后需要连接then()
函数
,以便捕获响应
变量
(axiostdata
)
有关更多信息,请参阅
请确保升级
//虚拟Url。
常量url=https://jsonplaceholder.typicode.com/posts/1'
//Axios测试。
const axiosTest=axios.get
//Axios测试数据。
axiosTest(url).然后(函数(AxiostResult){
console.log('response.JSON:'{
消息:“已收到请求”,
数据:AxiostResult.data
})
})
您可以在本文的“获取”部分找到check url和一些相关信息。对于客户端js代码来说,最重要的经验法则是将数据处理和ui构建逻辑分离到不同的函数中,这对于axios数据获取也是有效的。。。通过这种方式,您的控制流和错误处理将更加简单,也更易于管理,这一点可以从本文中看出
还有这个
函数getUrlParams(){
var url_params=新的URLSearchParams();
if(window.location.toString().indexOf(“?”)=-1){
var href_part=window.location.search.split(“?”)[1]
href_part.replace(/([^=&]+)=([^&]*)/g,
功能(m、键、值){
var attr=decodeURIComponent(键)
var val=解码组件(值)
url_params.append(attr,val);
});
}
//对于(url_params.entries()的变量对){consolas.log(对[0]+'->'+对[1])}而言
返回url_参数;
}
函数getServerData(url、urlParams){
if(typeof url_params==“undefined”){urlparms=geturlparms()}
返回axios.get(url,{params:urlParams})
。然后(响应=>{
返回响应;
})
.catch(函数(错误){
console.error(错误)
返回error.response;
})
}
//行动!!!
getServerData(url、url\u参数)
。然后(响应=>{
如果(response.status==204){
var warningMsg=response.statusText
console.warn(warningMsg)
返回
}else if(response.status==404 | | response.status==400){
var errorMsg=response.statusText//+“:“+response.data.msg//这是我的api
控制台错误(errorMsg)
返回;
}否则{
var data=response.data
变量数据类型=(数据类型)
如果(数据类型===‘未定义’){
var msg='获取数据时发生意外错误!!!'
//在此将消息传递给ui更改方法
//showmymmsg(msg,“错误”)
}否则{
var items=data.dat//obs这是我的api,也称为“dat”属性——这就是从中获取数据的json键
//在这里调用ui构建方法
//构建列表(项目)
}
返回
}
})
您可以使用一个简单的回调函数填充所需的数据,
假设我们有一个名为lst
的列表要填充,
我们有一个函数,可以生成列表
const lst = [];
const populateData = (data) => {lst.push(data)}
现在我们可以将回调函数传递给正在进行axios调用的函数,当我们从响应中获取数据时,我们可以对列表进行处理
现在,我们将发出请求并传递populateData
的函数作为回调函数
function axiosTest (populateData) {
axios.get(url)
.then(function(response){
populateData(response.data);
})
.catch(function(error){
console.log(error);
});
}
axios库创建一个Promise()对象。Promise是JavaScript ES6中的内置对象。当使用new关键字实例化此对象时,它将函数作为参数。这个函数依次接受两个参数,每个参数也是函数-resolve和reject
Promission执行客户端代码,由于Javascript异步流很酷,最终可能会解决一两件事,即解决方案(通常被认为在语义上等同于Promise的成功)或拒绝方案(被广泛认为是错误的解决方案)。例如,我们可以持有对某个Promise对象的引用,该对象包含一个最终将返回响应obj的函数
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
function getUrlParams (){
var url_params = new URLSearchParams();
if( window.location.toString().indexOf("?") != -1) {
var href_part = window.location.search.split('?')[1]
href_part.replace(/([^=&]+)=([^&]*)/g,
function(m, key, value) {
var attr = decodeURIComponent(key)
var val = decodeURIComponent(value)
url_params.append(attr,val);
});
}
// for(var pair of url_params.entries()) { consolas.log(pair[0]+ '->'+ pair[1]); }
return url_params ;
}
function getServerData (url, urlParams ){
if ( typeof url_params == "undefined" ) { urlParams = getUrlParams() }
return axios.get(url , { params: urlParams } )
.then(response => {
return response ;
})
.catch(function(error) {
console.error ( error )
return error.response;
})
}
// Action !!!
getServerData(url , url_params)
.then( response => {
if ( response.status === 204 ) {
var warningMsg = response.statusText
console.warn ( warningMsg )
return
} else if ( response.status === 404 || response.status === 400) {
var errorMsg = response.statusText // + ": " + response.data.msg // this is my api
console.error( errorMsg )
return ;
} else {
var data = response.data
var dataType = (typeof data)
if ( dataType === 'undefined' ) {
var msg = 'unexpected error occurred while fetching data !!!'
// pass here to the ui change method the msg aka
// showMyMsg ( msg , "error")
} else {
var items = data.dat // obs this is my api aka "dat" attribute - that is whatever happens to be your json key to get the data from
// call here the ui building method
// BuildList ( items )
}
return
}
})
</script>
const lst = [];
const populateData = (data) => {lst.push(data)}
function axiosTest (populateData) {
axios.get(url)
.then(function(response){
populateData(response.data);
})
.catch(function(error){
console.log(error);
});
}
const base_endpoint = BaseEndpoint + "cache/";
// Default function is going to take a selection, date, and a callback to execute.
// We're going to call the base endpoint and selection string passed to the original function.
// This will make our endpoint.
export default (selection, date, callback) => {
fetch(base_endpoint + selection + "/" + date)
// If the response is not within a 500 (according to Fetch docs) our promise object
// will _eventually_ resolve to a response.
.then(res => {
// Lets check the status of the response to make sure it's good.
if (res.status >= 400 && res.status < 600) {
throw new Error("Bad response");
}
// Let's also check the headers to make sure that the server "reckons" its serving
//up json
if (!res.headers.get("content-type").includes("application/json")) {
throw new TypeError("Response not JSON");
}
return res.json();
})
// Fulfilling these conditions lets return the data. But how do we get it out of the promise?
.then(data => {
// Using the function we passed to our original function silly! Since we've error
// handled above, we're ready to pass the response data as a callback.
callback(data);
})
// Fetch's promise will throw an error by default if the webserver returns a 500
// response (as notified by the response code in the HTTP header).
.catch(err => console.error(err));
};
// Make sure you import GetCache from GetCache.js!
resolveData() {
const { mySelection, date } = this.state; // We could also use props or pass to the function to acquire our selection and date.
const setData = data => {
this.setState({
data: data,
loading: false
// We could set loading to true and display a wee spinner
// while waiting for our response data,
// or rely on the local state of data being null.
});
};
GetCache("mySelelection", date, setData);
}
async function axiosTest() {
const response = await axios.get(url);
const data = await response.json();
}
async function axiosTest() {
try {
const {data:response} = await axios.get(url) //use data destructuring to get data from the promise object
return response
}
catch (error) {
console.log(error);
}
}
function axiosTest() {
axios.get(url)
.then(response => response.data)
.catch(error => error);
}
async function getResponse () {
const response = await axiosTest();
console.log(response);
}
getResponse()
function axiosTest() {
axios.get(url)
.then(response => response.data)
.catch(error => error);
}
async function getResponse () {
axiosTest().then(response => {
console.log(response)
});
}
getResponse()