Cant api connection doesnt work on production react native - reactjs

Before building the react native app to production, I was able to log in and I could get error messages for any errors but after building to apk, I ran the app on my android phone but It didn't work.
I am fetching the user login like this;
import { userTypes } from '../../types';
const { USER_LOGIN } = userTypes;
const SERVER_URL = "http://localhost:8080/api/v1";
const loginAction = (userdata) => dispatch => {
fetch(`${SERVER_URL}/auth/signin`,{
method: 'POST',
headers: {
'content-type' : 'application/json',
},
body: JSON.stringify(userdata)
})
.then(res => res.json())
.then(data =>(
dispatch({
type: USER_LOGIN,
payload: data
})))
}
export {
loginAction
};
Is there a proper way to use api connections both on development and production.

I guess you are using android 9. If it's the case try with this:
Add in your main AndroidManifest.xml
<manifest xmlns:tools="http://schemas.android.com/tools">
<application android:usesCleartextTraffic="true" tools:targetApi="28"> </application>
</manifest>

Related

my app is taking localhost:3000 as the server. but i have localhost:4000 as the server

My problem is that iam using axios to communicate with backend.axios had done perfect job till now. but when i wrote a code for register, my console says that
POST http://localhost:3000/api/v1/register 500 (Internal Server Error)
so till now it responded very good.but now it thrwing an error like this.
userAction.js :
export const register = (userData) => async (dispatch) => {
try {
dispatch({ type: REGISTER_USER_REQUEST });
const config = { headers: { "Content-Type": "multipart/form-data" } };
const { data } = await axios.post("/api/v1/register", userData, config);
dispatch({ type: REGISTER_USER_SUCCESS, payload: data.user });
} catch (error) {
dispatch({
type: REGISTER_USER_FAIL,
payload: error.response.data.message,
});
}
};
iam using localhost:4000 as server. but it showing me localhost:3000 which means my app url
Because you did not specify the host in your post url.Then it may be work.
/api/v1/register => http://localhost/api/v1/register
The if you have cors issue add this to the nodejs backend app.js file (as you using nodejs):
const cors = require('cors');
app.use(cors())

Why is my redirect to my frontend not working (Express and React)

I have a react frontend that sends data to backend and then in the backend I save the data, however when i redirect to another page after saving to database it does not go, however , the data is actually saved in the database. Below is the code
index.js (Backend)
app.post('/saveImg' , async (req , res) => {
const {image} = req.body
const cropData = new CropInfo({
image: image
})
//Save the entry
await cropData.save()
res.redirect('http://localhost:3000/login')
})
This is how the frontend is sending the data
const confirmPicture = () => {
//THIS IS WHERE I WANT TO INSERT THE CODE TO SEND Image TO BACKEND
axios({
method: "POST",
url: "http://localhost:4000/saveImg",
data: {
image: imgSrc
}
})
.then(res => {
console.log("res", res.data.message);
})
.catch(err => {
console.log("error in request", err);
})
}
I have a react route http://localhost:3000/login which loads a login page however for some reason the redirect in the backend is not working. Any advice on how to make it work? Am i doing anything wrong?
Send the response back to frontend like res.json({message: "ok"}) and in react do programatically redirect based on the response back.
import { useNavigate } from "react-router-dom";
const navigate = useNavigate()
fetch(URL,{OPTIONS})
.then(res => res.json())
.then(
(result) => {
if(result.message === "ok") {
navigate("/login");
}
})
If you are using axios:
axios.post(URL, {...})
.then(function (response) {
if(response.message === "ok") {
navigate("/login")
}
})

Using Rapid API Google Translate API with React Project

So I am making a React Component that uses the Google Translate API to translate text to different languages using a FormControl (Material UI). When I try to connect to the API on RapidAPI, I keep getting a 401 error.
Here is my code for connecting the the API and its use in App.js
useEffect(() => {
getLanguageData(text, language)
.then((data) => {
console.log(data);
})
}, [text, language]);
import axios from "axios";
const URL = 'https://google-translate1.p.rapidapi.com/language/translate/v2';
export const getLanguageData = async(text, language) => {
try {
// response goes here
const data = await axios.post(URL, {
headers: {
'content-type': 'application/x-www-form-urlencoded',
'x-rapidapi-host': 'google-translate1.p.rapidapi.com',
'x-rapidapi-key': '672f444ba1msh5ef96f3113280dep176206jsnb157cac756a8'
},
data: {q: text, target: language}
});
} catch(error) {
console.log(error);
}
}

React Native axios api call Shopify

Good morning guys, I try to fetch data from Shopify using this method. But it does not working.
Request failed with status code 400
May you share your little experience ?
I'm working on React Native Project.
const api_key = "example-api-key";
const password = "example-password";
const version = "2021-07";
const url = `https://${api_key}:${password}#store-example.myshopify.com/admin/api/${version}/products.json`;
useEffect(() => {
axios({
method:'get',
url:url
}).then((result) => {
console.log(result.data)
}).catch(error => {
console.log(error)
})
});
It's most likely that the authentication is failing. Move the auth parameters to axios header. Try this
const username = "example-api-key";
const password = "example-password";
const version = "2021-07";
const url = `https://store-example.myshopify.com/admin/api/${version}/products.json`;
useEffect(() => {
axios({
method:'get',
url,
auth: { username,password }
}).then((result) => {
console.log(result.data)
}).catch(error => {
console.log(error)
})
});

My axios instance does not work and I do not know why

I have created a seperate axios.js file for an axios instance to make requests to an API I have running live. When I use the axios instance in my login route I get a
POST http://127.0.0.1:3000/login 404 (Not Found) error, even though the url defined in my axios instance is not my localhost it is the url of the API. Now, when I use axios in my login route and enter the whole API url instead of using the instance, the POST request goes to the correct url and I get proper response. I do not understand this. Everything on the API is fine and has been tested many times AND I have used an axios instance like this before.
here is the instance I have set up(baseUrl is correct in my code):
import axios from 'axios';
const axiosInstance = axios.create({
baseUrl: REMOVED,
headers: {
Authorization: localStorage.getItem('accessToken')
? 'Bearer ' + localStorage.getItem('accessToken')
: null,
'Content-Type': 'application/json',
},
});
export default axiosInstance;
here is the login function that uses my axios instance and does not work:
export const login = (email, password) => (dispatch) => {
axiosInstance
.post('/login', { email: email, password: password })
.then((res) => {
dispatch({
type: LOGIN_SUCCESS,
payload: res.data,
});
})
.catch((err) => {
console.log(err);
dispatch({
type: LOGIN_FAIL,
});
});
};
here is the login function that works perfectly:
export const login = (email, password) => (dispatch) => {
axios
.post('fullurlnotshown/login', { email: email, password: password })
.then((res) => {
dispatch({
type: LOGIN_SUCCESS,
payload: res.data,
});
})
.catch((err) => {
console.log(err);
dispatch({
type: LOGIN_FAIL,
});
});
};
EDIT: SOLVED THE PROBLEM... 'baseUrl:' in the instance should be 'baseURL:'
You may be referencing the wrong property of baseUrl. The axios documentation has the property as baseURL (URL instead of Url).
Axios is probably silently ignoring your incorrect property key and falling back to localhost.

Resources