how to Make Http request from reactjs ?

試著忘記壹切 提交于 2019-12-01 11:29:20

I use axios. It allows you to set some default configuration so that you don't need to do it with every request:

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

There are many npm modules for http request. Here is a smiple one: 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);
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!