Friday 1 April 2022

Http API Base url set up in React and Angular

 React:

Soln:1

=======
api.js
import axios from "axios";
const api = axios.create({
 baseURL: process.env.REACT_APP_BASE_URL || "http://localhost:3000",
});

export default api;

import api from "../services/api";
const response = await api.post("/sessions", { email, password });

Soln:2
=======
import Axios from "axios";

Axios.defaults.baseURL = "http://127.0.0.1:8000/api/";

in any other components use

insted of http://127.0.0.1:8000/api/user use only user

axios.get('user')  // just 'user' append the data
.then((res)=> {
console.log(res)
})

Angular:
-----
environment.ts

export const environment = {
production: false,
baseUrl: 'http://fakerestapi.azurewebsites.net/api'
};
environment.prod.ts file
export const environment = {
production: true,
baseUrl: 'https://jsonplaceholder.typicode.com'
}

refer baseUrl from environment.ts file 

import { environment } from '../environments/environment';
@Injectable()
export class DataService {
baseUrl = environment.baseUrl;
constructor(private httpClient: HttpClient) { }
getUser(id: number) {
let url = this.baseUrl + '/users/1';
return this.httpClient.get<JSON>(url);
}
}

No comments:

Post a Comment