axios not fetching API - reactjs

Hi I am trying to fetch data from backend using an api but the api is returning 404 error. In postman it is working fine. Can someone look in the code and tell where am I going wrong:
import axios from "axios";
function fetchData(email, password) {
var url = "http://localhost:4000/api/v2/auth/sign_in";
var payload={email:email,password:password};
axios.post(url,payload)
.then((res)=>{console.log(res)})
.catch((err)=>{alert(err)})
}
export default fetchData;

Related

Axios api call gives Network error while fetch() works well

I'm a react native beginner. I'm trying to make a simple http get request using axios.
Here is my axios configuration:
import axios from 'axios';
export default axios.create({
baseUrl: 'https://blobrfishwebapi.azurewebsites.net',
});
And this is how I make the request using my configured axios:
import configuredAxios '../api/configuredAxios';
const response = await configuredAxios
.get('/employer/jobposts/recenttest')
.then(res => res.data)
.then(({data, isSuccessful, message}) => {
if (!isSuccessful) {
throw new Error(message);
}
setjobPostings(data);
})
.catch(err => {
console.log(JSON.stringify(err, Object.getOwnPropertyNames(err)));
});
This is the error I get when I make the above call:
{"stack":"Error: **Network Error**\n at createError (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.blobfshemployer&modulesOnly=false&runModule=true:98386:17)\n at XMLHttpRequest.handleError (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.blobfshemployer&modulesOnly=false&runModule=true:98196:69)\n.....
Finally, same endpoint call using fetch() which returns a 200 status code:
let response = await fetch(
'https://blobrfishwebapi.azurewebsites.net/employer/jobposts/recenttest',
);
let json = await response.json();
setjobPostings(JSON.stringify(json, Object.getOwnPropertyNames(json)));
catch(
err => console.log(JSON.stringify(err, Object.getOwnPropertyNames(err))),
console.log('error'),
);
Has anyone experienced a similar problem using axios?
I'm running my app on an android emulator, axios version is 0.21.4, react native version is 0.70.4.
Thanks in advance.
Rookie error! The "baseUrl" property of my axios config object should have the "url" part capitalized:
import axios from 'axios';
export default axios.create({
base**URL**: 'https://blobrfishwebapi.azurewebsites.net',
});

How access server side cookies in a axios intercepor and outside of getServerSideProps()

In my nextjs app, I created a separate file for my axios interceptors and I'm making a request in getServerSideProps() which needs to have a Authorization header with some access token. I'm doing the logic for attaching headers inside mu interceptors but I need to access the cookie outside of getServerSideProps() and in my interceptor. Is there a way to achieve this behavior?
Late answer but may be useful for someone. You'll need to create an API route to retrieve the cookie as usually you'll need to pass the req and res to the cookie lib you're using like cookies-next.
So you create a route like /api/token and then place a code like this:
import { getCookie } from 'cookies-next';
import type { NextApiRequest, NextApiResponse } from 'next';
export default function handler(req: NextApiRequest, res: NextApiResponse) {
const token = getCookie('site-jwt', { req, res });
res.status(200).json({ token });
}
and then in your interceptor, you do a fetch
const { token } = await fetch('/api/token').then(r => r.json())

Laravel backend API, react frontend login

I am trying to do the following:
User clicks a link to URL site from react (say google.com)
User enters his credentials on a pop-up form using react's simple oauth
import React from 'react';
import ReactDOM from 'react-dom';
import OAuth2Login from 'react-simple-oauth2-login';
const onSuccess = response => console.log(response);
const onFailure = response => console.error(response);
ReactDOM.render(
<OAuth2Login
authorizationUrl="https://accounts.spotify.com/authorize"
responseType="token"
clientId="9822046hvr4lnhi7g07grihpefahy5jb"
redirectUri="http://localhost:3000/oauth-callback"
onSuccess={onSuccess}
onFailure={onFailure}/>,
document.getElementById('root')
);
The site returns to me a JSON with the users data (on a specific URL user/callback)
Laravel (after the callback is read from my routes file) does the following:
public function handleProviderCallBackMel(Request $request)
{
return reponse()->json($jsonUser,200);
}
That's working A-OK with Laravel. Laravel get the response (the token and the user data that I need). BUT I can't pass that information back to react.
How do I pass that data to my front end react app from my backend laravel app that got the callback information I need?

Fetching data with the endpoint from AWS using React js

I am using axios to fetch data from aws.
import React, {useState, useEffect} from 'react';
import axios from 'axios';
function Employee() {
const[data, setData] = useState([]);
useEffect(() => {
axios.get('123.56.234.123:8080/employees?num=1')
.then(response => {
setData(response.data);
})
},[]);
return data;
}
From this code, I got the error message saying
Get http://localhost:8080/123.56.234.123:8080/employees?num=1 431(Request Header Fields Too Large).
I believe the cause is from the wrong url I am getting.
In this case, how can I fetch data from the endpoint?
PS) My node version: 14.XX
Thank you.
I think you need to set a PROXY. You have currently set the axios baseURL to be localhost:8080. That is why the get url is getting prepended to baseUrl.
The error 431(Request Header Fields Too Large) occurs because the Referrer url is too long.
If you are using create-react-app, then please refer this official documentation.

in my js file with axios when i try to post some test data to firebase, i am getting some error

when I tried to post some random data to firebase through axios from the js file, the error shown is given below.
_axios_order__WEBPACK_IMPORTED_MODULE_2___default.a.post is not a function.
the code is
//all import statements including axios and there is an axios file and it contains an axios baseURL.And the class definition.
purchasecontinueHandler=()=>{
const order={
ingredients:this.state.ingredient,
price:this.state.burgerprice,
}
axios.post('/orders.json',order)
.then(response => console.log(response))
}
this was my mistaken code, here I exported the 'instance' with a new method, unfortunately, that was not required.
import axios from 'axios';
const intsance=axios.create({
baseURL:'https://burger-d4f0a.firebaseio.com/'
});
export default new intsance();
just define as
import axios from 'axios';
const intsance=axios.create({
baseURL:'https://burger-d4f0a.firebaseio.com/'
});
export default intsance;

Resources