作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我使用 npm 模块“create-react-app”创建了 React 应用程序
我想使用外部 API 来表示 api.example.com
,但无法调用外部 API,因为 axios 请求的是 localhost 而不是外部 API。
我尝试了以下代码:
class Example extends Component{
static defaultProps={
'url':"api.example.com"
}
handleChange(event){
axios.get(this.props.url+event.target.value)
.then(result=> console.log(result.data)
}
}
}
如何让React应用程序访问外部API?
最佳答案
例如,在数据库中添加一些产品的 POST 请求:
在示例中,我使用 JWT 身份验证来访问 API。
JSON.stringify
没有必要使用,因为axios已经实现了这个功能,这里使用它是为了更好的理解。不要在生产中使用它!
const jwtToken = 'd70414362252a41ceger5re435gdgd45hjk';
const data = JSON.stringify({
id: '5',
title: 'product'
price: '15000',
description: 'string',
});
const configAxios = {
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer + ${jwtToken}`,
},
};
axios.post('https://api.somesite.com/products', data, configAxios)
.then((res) => {
this.date.description = res.data;
console.log(res);
})
.catch((err) => {
console.warn('error during http call', err);
});
还需要注意的是,我们严格在代码中写入 JWT token ,尽管必须定期接收它,但这在本示例中并未实现。
关于javascript - 如何在 React 中使用外部 api,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48825746/
我是一名优秀的程序员,十分优秀!