如何从 reactjs 发出 Http 请求?

IT技术 database reactjs zend-framework httprequest zend-framework3
2021-05-21 00:06:42

我在 ToDo 应用程序中使用 react js 作为前端,使用 zf3 作为后端。我把我所有的 React 文件夹和文件放在 Zend 项目的公共文件夹中。截至目前,它只是简单的应用程序,没有数据库连接。现在我想添加 Db 来存储任务。但是作为新手,我不知道如何发出编辑删除和添加任务的Http请求。请举例说明。任何帮助将不胜感激。谢谢你。

3个回答

我使用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

http 请求有很多 npm module。这是一个简单的:https : //github.com/request/request

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);
});