laravel react native axios post - react-native

i have a react native app as the front end and am trying to implement login, on localhost i can login well but in production i get the error the GET method is not supported on this route supported methods POST. When i test the endpoint using thunder client from VS code it works but in my react native app i get the route not supported error.
react native code:
export const loginuser = (username,password) =>{
return async(dispatch)=>{
dispatch({type:REG_LOADER})
const headers = {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
axios.post(ROOT_URL+"login/saler", {
username:username,
password:password,
},{headers:headers})
.then( async(response) => {
console.log(response.data)
dispatch({type:LOGIN_FAIL})
let user = response.data.customer
let status = response.data.status
if(status === "1"){
await AsyncStorage.setItem('userdata', JSON.stringify(user))
dispatch({type:LOGIN_SUCCESS,payload:user})
}else{
alert('Wrong phone number or password')
dispatch({type:LOGIN_FAIL})
}
})
.catch(function (error) {
alert(error.response.data.message)
dispatch({type:LOGIN_FAIL})
})
}
}
laravel route:
Route::group(['prefix' => 'v1', 'as' => 'api.', 'namespace' => 'Api\V1\Sales'], function () {
Route::post('/login/saler','Auth\LoginController#Login');
]);
enter code here

Related

React native Expo project, Fetch the API will get [TypeError: Network request failed], but the others api can work

When I fetch the api in React native Expo project will get [TypeError: Network request failed].
I have try to fetch other API, it can get data success.
And also try to fix by this question but didn't work for me.
(Also tried this React Native fetch() Network Request Failed)
Is API's problem?
My code like:
const val = { uId: 'molly', pwd: '123', id: '1' }
const url = 'https://c........com.tw:8899'
let header = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(val),
}
fetch(`${url}/auth/login`, header)
.then((r) => r.json())
.then((d) => {
if (d.code === 0) {
console.log(d.data)
} else {
console.log('MSG', d.msg)
}
})
.catch((err) => console.log(err))
And I have try this, it can work. (So is not the network problem.)
fetch('https://randomuser.me/api/')
.then((r) => r.json())
.then((d) => {
console.log('ok')
})
.catch((err) => console.log(err))
Thanks for any suggestion.
I found the problem is about ssl.
Should use this package to deal with
react-native-ssl-pinning
https://www.npmjs.com/package/react-native-ssl-pinning

axios Post returning error in react native

i am using react native as front-end and backend i have laravel
i am tring to make a axios post request to api my api is working fine in postman
function getdata() {
const Data = {
name: name,
email: email,
date: mydate,
};
console.log(Data);
axios
.post('http://127.0.0.1:8000/api/users', Data)
.then(() => {
alert('success submited');
})
.catch(error => {
alert(error);
});
}
error :axiosError:Netwoek Error

How to access SEA module in GUNJS without using dynamic require in React Native expo

So I've started this new project using React Native(Expo), and I've imported all packages including GunJS and SEA, however, when I run the app, I get the error that dynamic require is not supported by Metro. I checked the sea.js file and found that the devs use require(arg), which is not supported by React Native. This is a huge bummer and I haven't found any workaround. Is there any other way to access SEA?
import GUN from "gun";
import "gun/sea";
import { userContext } from "../global";
export const gun = GUN();
The below snippet is the sea.js file, which uses dynamic require.
/* UNBUILD */
function USE(arg, req){
return req? require(arg) : arg.slice? USE[R(arg)] : function(mod, path){
arg(mod = {exports: {}});
USE[R(path)] = mod.exports;
}
We got this fixed in the latest GitHub main (hopefully published soon).
Thanks to Aethiop! Who also wrote a great tutorial on this:
https://github.com/aethiop/jot
if you need to use SEA in react-native now without wait the gun community to fix this problem do this build API with nodejs and install gun in after going in your react-native app call this API
see ex:
//nodejs that manage sea so in my case I use auth feature sea
const fastify = require("fastify")();
const Gun = require('gun'); // in NodeJS
require('./sea/sae');
const gun = new Gun ({
peers: ['https://gun-serve.herokuapp.com/gun'],
})
const user = gun.user()
const ADDRESS = "0.0.0.0";
const PORT = process.env.PORT || 3000;
fastify.get("/", function (req, reply) {
reply.send("wellcome");
});
fastify.post('/userregist', async (request, reply) => {
try {
user.create(`${request.body.user}`,`${request.body.password}`, ({ err , pub}) => {
if (err) {
return reply.code(200).send({ "err": `${err}`})
} else {
return reply.code(200).send({"pub": `${pub}`})
}
});
} catch (error) {
request.log.error(error);
return reply.send(500);
}
})
fastify.post('/userlogin', async (request, reply) => {
try{
user.auth(`${request.body.user}`,`${request.body.password}`, ({ err, get, }) => {
if (err) {
return reply.code(200).send({ "err": `${err}`})
} else {
console.log('joshau get', get)
return reply.code(200).send({"pub": `${get}`})
}
});
} catch (error) {
request.log.error(error);
return reply.send(500);
}
})
fastify.listen(PORT, ADDRESS, (err, address) => {
if (err) {
console.log(err);
process.exit(1);
}
});
so i call api my app like that:
//my call api
const loginRequest = async (email, password) => {
try {
return await fetch('https://locahost:3000/userlogin', {
mode: 'no-cors', method: 'POST',
headers: {
'Content-type': 'application/json',
'Accept': ' application/json'
},
body: JSON.stringify({
user: email,
password: password,
}),
})
} catch (error) {
return error;
}
};
// here is way i call it i comp
LoginRequest(email, password)
.then((res)=> {
res.json().then(function (text) {
if(text.err){
LOADING_STOP()
alert(`${text.err}`)
console.log('error message',text.err)
}else{
console.log('public key',text.pub)
LOADING_STOP()
navigation.replace("Dashboard");
}
}).catch((e)=> {
LOADING_STOP()
alert(e)
})
put import shim from "gun/lib/mobile"
at the top of your file. (before the SEA import) :D !
import shim from "gun/lib/mobile"
import SEA from 'gun/sea'

Twitch API 401 error with React Native Expo

I'm trying to get user info from Twitch with React Native Expo, but it always returns 401 error.
I found that it correctly gets the OAuth token, but the problem occurs after it.
Here's my code:
WebBrowser.maybeCompleteAuthSession();
// Endpoint
const discovery = {
authorizationEndpoint: 'https://id.twitch.tv/oauth2/authorize',
tokenEndpoint: 'https://id.twitch.tv/oauth2/token',
revocationEndpoint: 'https://id.twitch.tv/oauth2/revoke',
};
// Login Screen
export function loginScreen({ navigation }) {
const [request, response, promptAsync] = useAuthRequest(
{
responseType: ResponseType.Token,
clientId: '(deleted)',
// For usage in managed apps using the proxy
redirectUri: makeRedirectUri({ useProxy: true }),
scopes: ['openid', 'user_read', 'user_subscriptions'],
},
discovery
);
React.useEffect(() => {
if (response?.type === 'success') {
fetch('https://api.twitch.tv/kraken/user', {
method: 'GET',
headers: {
'Accept': 'application/vnd.twitchtv.v5+json',
'Client-ID': '(deleted)',
'Authorization': 'OAuth ' + response.params
}
})
.then((data) => {
AsyncStorage.setItem('userData', JSON.stringify(data))
.then(() => console.log(JSON.stringify(data))) // console.log for testing
.then(() => navigation.navigate('Home'))
})
.catch((err) => alert(err))
}
}, [response]);
and I referred to this document for the authentication.
Twitch SignIn & get user information using Expo's expo-auth-session.
Step 1: Create an account and enable two-factor authentication on Twitch developer site.You will get a key.
Step 2: Install Expo's expo install expo-auth-session
Step 3: Add Scheme in App.json file
{
"expo": {
"scheme": "myapp"
}
}
In order to be able to deep link back into your app, you will need to set a scheme in your project app.config.js, or app.json, and then build your standalone app (it can't be updated with an OTA update). If you do not include a scheme, the authentication flow will complete but it will be unable to pass the information back into your application and the user will have to manually exit the authentication modal (resulting in a cancelled event).
Step 4:
import * as AuthSession from 'expo-auth-session';
// To fetch twitch user information
const getTwitchUserInformation = twitchToken => {
const url = 'https://api.twitch.tv/helix/users';
const header = {
Authorization: `Bearer ${twitchToken}`,
'Client-ID': SOCIAL_CONSTANTS.TWITCH_CLIENT_ID,
};
fetch(url, {
method: 'GET',
headers: header,
})
.then(response => response.json())
.then(response => {
const userResponse = response && response.data[0];
console.log(userResponse);
})
.catch(error => {
console.log(error);
});
};
const signInWithTwitch = async () => {
const redirectUrl = AuthSession.getRedirectUrl();
const authUrl = `https://id.twitch.tv/oauth2/authorize?client_id=${ENTER_CLIENT_ID_HERE}&redirect_uri=${redirectUrl}&response_type=token&scope=user:edit+user:read:email&force_verify=true`
const {type, params} = await AuthSession.startAsync({authUrl});
if (type === 'success') {
const {access_token, token_type} = params;
getTwitchUserInformation(access_token);
}
};
Link - https://medium.com/#rakesh.medpalli/twitch-signin-get-user-information-in-expo-using-expo-auth-session-a6a74812c096

React Native - Axios POST with urlencoded params

I successfully triggered POST request via Postman to retrieve mobileSession key. But when I tried the same from React Native app (via Axios), I get error that some params are missing. Can someone tell me what is wrong in Axios according to Postman request which is working?
Postman:
And Axios code:
export function getMobileSession() {
let requestOptions = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
};
let body = {
username: 'myusername',
password: 'mypw',
api_key: 'apikey',
api_sig: 'signature',
method: 'auth.getMobileSession',
format: 'json'
};
return axios.post('Lastfm_API_URL', JSON.stringify(body), requestOptions)
.then(response => {
return response;
})
.catch(err => {
throw err;
});
}
Try this,
return axios.post(`https://ws/audioscrobbler.com/2.0/`, JSON.stringify(body), requestOptions)
.then(response => {
return response;
})
.catch(err => {
throw err;
});
For more refer here to know about back tick.