how to Make Http request from reactjs ? - database

I am using react js as front end and zf3 as a backend in my ToDo application. I put all my React folder and files in public folder of Zend project. As of now, it is just Simple app there is no database connection. Now I want to add Db for storing tasks. but as a newbie, I don't know how to make Http request for edit delete and add a task. please explain with a example. Any help will be appreciated. Thank you.

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

Related

How to hide authorization bearer token from header?

I want to hide some information such as bearer token and API key in header. I have been heard about ssr and using proxy to hide that information, but how? Can someone tell me how to do that? Or is that possible to do in client side?
I tried with some ssr that fetch in react, but it doesn't work for me. I also tried with proxy, but that works for API key that didn't need a dynamically params like user token.
To use server-side rendering (SSR), you will need to install and import the following packages: express, cors, and Axios. The cors middleware allows for Cross-Origin Resource Sharing, while Axios is used to make HTTP requests to external APIs or databases, and handle the response data asynchronously. By setting the headers with Axios, you can pass along sensitive information such as API keys and bearer tokens. After receiving the data back, you can destructure it from the Axios response and then send it back to your users by using the res.json() method.
const cors = require('cors');
const axios = require('axios');
const app = express();
app.use(cors());
app.get('/api/data', async (req, res) => {
try {
const { data } = await axios.get('https://api.example.com/data', {
headers: {
Authorization: `Bearer ${process.env.BEARER_TOKEN}`,
'API-Key': process.env.API_KEY,
},
});
res.json(data);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
app.listen(3000, () => {
console.log('Server started on port 3000');
});

Axios returns NetworkError / CORS Headers enabled

I build a ionic-react android application with Axios to get a server response. Two weeks ago my code was working fine. Now the axios request always returns a NETWORK_ERR (HttpError or Axios Error).
I tried to use all CORS Headers possible in my api, but the request is not sent to the webservice.
I hope anyone can help me:
This is the Code I was using:
const api = axios.create({
baseURL: "http://192.168.0.145:8080/RestFulTest-1.0-SNAPSHOT/api",
});
function callApi(){
api.get("/verification")
.then((res) => {
console.log(res);
})
.catch((error) => {
console.log(error);
});
}
Just directly opening the API Url in browser is not loading it...
Sot it seems either the backend is down or blocking and requires an authorization header with the axios request, like
let tokenStr = "Your TOKEN";
axios.get("/verification", { headers: {"Authorization" : `Bearer ${tokenStr}`} });
Hope it helps..

React: how to use axios/fetch to get data from API that runs on localhost?

I have a spring-boot rest API that I run on my http://localhost:8080. I am building a frontend in React, and I would like to use the API, but something is not working.
I have this code:
componentDidMount() {
axios.get('https://jsonplaceholder.typicode.com/users')
.then(res => {
console.log(res);
});
axios.get('http://localhost:8080/api/player')
.then(res => {
console.log(res);
});
}
The first axios() works, the second not. I don't see a reason what the difference is... My spring-boot app does not even get the GET request, or else it would log it.
Use this cors set up for your #Controller
#CrossOrigin(allowedHeaders = "*", origins = "http://localhost:4200")
#GetMapping(value = "/api/player")
public ResponseEntity<?> myMethod(...) {
//do things
...
}
and add cors to your header request:
axios.get('http://localhost:8080/api/player',{
headers: {"Access-Control-Allow-Origin": "*"}
}).then(res => {
console.log(res);
});
or disable cors in your spring security config:
http.cors().and().csrf().disable().headers().and().authorizeRequests().antMatchers("/api/player").permitAll()
.anyRequest().authenticated();

Cannot make a GET request in Postman with React

I created a joke generator app that takes jokes from a local json file with data that I created and displays it in the browser. This app has no backend at all. I am trying to make a GET request through Postman, but no luck. Is it even possible to use postman in this scenario?
NO Postman is not used for programmatic api calls. Use axios for this. Suppose your server is running on localhost:3000.
npm install axios
In your component,
const axios = require('axios');
// Make a request for a user with a given ID
axios.get('/jokes?id=1')
.then(function (response) {
// handle success
console.log(response);
})
.catch(function (error) {
// handle error
console.log(error);
})
.then(function () {
// always executed
});

How to ignore SSL issues in axios using React Native?

Hi I'm currently working with react native on Android with Expo. I am trying to send requests to my server which has a valid ssl certificate, but for some reason axios takes it as invalid, so axios does not allow me to send requests to my server's api.
this is the error i get:
Error: Network Error
So I wonder if there is any way to make axios ignore the problem with the ssl and can send the requests in a normal way
this is my code:
try {
const headers = {
'Accept-Language': 'es-ES,es;q=0.8',
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "application/json",
};
axios.get("https://URLtoMySERVER", {}, headers)
.then(response => {
console.log(response)
const posts = response.data;
console.log(posts)}
).catch(function(error) {
console.log("error", error);
});
} catch (error) {
console.log('err', error);
}
some points that I want to clarify:
1- I can't use RNFetchBlob because I'm using Expo, and RNFetchBlob have some native libraries.
2- I can't use httpsAgent either with axios because apparently https library does not work with expo, or at least it does not work for me.
3- fetch doesn't work either
Is there any other alternative to axios or fetch that works in react native with expo and where you can ignore the problems of https?

Resources