我是第一次使用unirest
API调用和React,但是在实现unirest
调用时遇到了麻烦。虽然它可以在简单的Node.js程序中运行,但是如果我尝试将下面的代码插入React.js文件并使用它,由于某种原因,我将无法获得任何结果,因为我只是获得了一个未定义的对象
var unirest = require('unirest');
unirest.get(--insert url here--)
.header("X-Mashape-Key", --insert key here--)
.header("X-Mashape-Host", "spoonacular-recipe-food-nutrition-
v1.p.mashape.com")
.end(function (result) {
console.log(result.status, result.headers, result.body);
});
但是,当我将其插入准系统Node.js文件中时,我会得到一个带有所需值的对象。我已经为此苦苦挣扎了好几天-有人知道我在做什么错吗?
编辑:这是我尝试在React中实现此方法的方法:
import React from 'react';
import './App.css';
var unirest = require('unirest');
class Kitchen extends React.Component {
callApi() {
unirest.get(--insert api url--)
.header("X-Mashape-Key", --insert api key--)
.header("X-Mashape-Host", "spoonacular-recipe-food-nutrition-
v1.p.mashape.com")
.end(function (result) {
console.log(result.status, result.headers, result.body);
});
render() {
return(
<div className="ingredient-info">
{this.callApi()}
</div>
)
}
编辑2:这是预期的对象主体的外观:
[ { id: 556470,
title: 'Apple fritters',
image: 'https://spoonacular.com/recipeImages/556470-312x231.jpg',
imageType: 'jpg',
usedIngredientCount: 3,
missedIngredientCount: 0,
likes: 243 },
{ id: 73474,
title: 'Apple Turnovers',
image: 'https://spoonacular.com/recipeImages/73474-312x231.jpg',
imageType: 'jpg',
usedIngredientCount: 3,
missedIngredientCount: 0,
likes: 48 },
{ id: 47950,
title: 'Cinnamon Apple Crisp',
image: 'https://spoonacular.com/recipeImages/47950-312x231.jpg',
imageType: 'jpg',
usedIngredientCount: 3,
missedIngredientCount: 0,
likes: 35 } ]
答案 0 :(得分:1)
Unirest是针对Node(服务器端)的...客户端(浏览器)已在其中获取...
以下是https://randomuser.me/示例的简单获取请求:
class App extends Component {
state = { users: [] };
componentDidMount() {
fetch("https://randomuser.me/api/?results=10&nat=us")
.then(results => results.json())
.then(data => {
const users = data.results;
this.setState({ users: users });
})
.catch(err => console.log(err));
}
render() {
return (
<div>
{this.state.users.map((user, index) => {
return (
<div key={index}>
<div>{user.name.first}</div>
<img src={user.picture.thumbnail} alt="" />
</div>
);
})}
</div>
);
}
}
以下是一个可行的示例:https://codesandbox.io/s/0yw5n3mm7n