【问题标题】:how to Make Http request from reactjs ?如何从 reactjs 发出 Http 请求?
【发布时间】:2017-03-09 16:08:15
【问题描述】:
我在 ToDo 应用程序中使用 react js 作为前端,使用 zf3 作为后端。我把我所有的 React 文件夹和文件放在 Zend 项目的公共文件夹中。截至目前,它只是简单的应用程序,没有数据库连接。现在我想添加 Db 来存储任务。但作为一个新手,我不知道如何进行 Http 请求进行编辑删除和添加任务。请举例说明。任何帮助将不胜感激。谢谢。
【问题讨论】:
标签:
database
reactjs
zend-framework
httprequest
zend-framework3
【解决方案1】:
我使用axios。它允许你设置一些默认配置,这样你就不需要对每个请求都这样做:
axios.defaults.headers.common.Authorization = "my-awesome-token";
axios.defaults.baseURL = http://www.somehost.com/api;
...
axios.get('/people')
.then(response => handleResponse(response))
.catch(error => handleError(error))
// actually shoots to http://www.somehost.com/api/people with Authorization header
【解决方案3】:
install axios
$ npm install axios
import axios
import axios from 'axios';
get request
axios.get('api url').then(function (response) {
console.log(response);
}).catch(function (error) {
console.log(error);
});
post request
var body = {
firstName: 'testName',
lastName: 'testLastName'
};
axios.post('api url',body).then(function (response) {
console.log(response);
}).catch(function (error) {
console.log(error);
});