React-native axios with ColdFusion component - react-native

I'm trying to send a get request from react native, using axios, to my coldfusion component.
My coldfusion component:
component displayName="react" {
remote any function ajaxLogin(data) returnformat="JSON"{
data = deserializeJSON(arguments.data);
return serializeJSON(login(data));
}
private any function login(data){
loginQuery = new query();
loginQuery.setDatasource("ds");
loginQuery.setName("loginQuery");
loginQuery.addParam(name="UserEmail", value="#arguments.data.userEmail#", cfsqltype="cf_sql_varchar");
loginQuery.addParam(name="UserPW", value="#arguments.data.userPassword#", cfsqltype="cf_sql_varchar");
result = loginQuery.execute(sql="SELECT * FROM Users Where UserEmail = :UserEmail AND UserPW = :UserPW");
rs = result.getResult();
if(rs.recordCount == 0){
return 0;
} else {
return rs.UserID;
}
}
}
My react-native dispatch action:
export const loginUser = ({ email, password }) => {
// login
return (dispatch) => {
dispatch({ type: 'TEST' });
axios.get('https://myserver.com/components/reactNative/react.cfc?method=ajaxLogin', {
params: {
userEmail: email,
userPassword: password
}
})
.then((response) => {
console.log(response.data);
})
.catch((err) => {
console.log(err);
});
};
};
It is returning an error from the catch:
Error: Request failed with status code 500
I am new with axios and react-native. Am I using axios wrong?
Thanks

Status code 500 is a server-side error so you're likely getting a Coldfusion error, check your ColdFusion logs.
Also as you're calling this as a GETrequest you can just open the URL in a browser tab and see if you get any errors dumped to the page (in a development environment)
https://myserver.com/components/reactNative/react.cfc?method=ajaxLogin&userEmail=email&userPassword=password
If this is production then you should see errors in your error logs (somewhere like /var/www/opt/coldfusion_11/cfusion/logs on linux)

Related

node_modules/#tanstack/query-core/build/lib/mutation.js:153:10 in Mutation#execute react native expo

I'm buiding React Native Expo App with external rest api.
I have created reusable axios api call:
// axiosAPi.js
export const axiosApi = async (method, url, obj = {}) => {
try {
switch (method) {
case 'GET':
return await axios
.get(`${baseUrl}/${url}`, config)
.then((res) => res.data)
case 'POST':
return await axios
.post(`${baseUrl}/${url}`, obj, config)
.then((res) => res.data)
case 'PUT':
return await axios
.put(`${baseUrl}/${url}`, obj, config)
.then((res) => res.data)
case 'DELETE':
return await axios
.delete(`${baseUrl}/${url}`, config)
.then((res) => res.data)
}
} catch (error) {
throw error?.response?.data?.error
}
}
I have created a hook with login instance using react-query:
// api/index.js
export default function useApiHook() {
const login = useMutation((obj) => axiosApi('POST', `auth/login`, obj))
return { login }
}
Here is the implementation of login screen
// screens/login.js
const loginPostMutation = useApiHook()?.login
const submitHandler = (data) => {
loginPostMutation
?.mutateAsync(data)
?.then((res) => res)
.catch((err) => err)
}
When I send correct credentials is returns the data with no errors, but when I send incorrect credentials it returns the error + this warning in the console:
Invalid credentials
at node_modules/#tanstack/query-core/build/lib/mutation.js:153:10 in Mutation#execute
The line in question points towards react-query logging the error to the console in development mode. Invalid credentials is thus just an error that is returned from axios, very likely, a 401 - Unauthorized error.
You would very likely get the same error when making the axios request without react-query.

Svelte (Express & Axios) - http 500 error on put method

I'm at a loss. I have a svelte application (Backend: Express, Frontend: Axios). I have a MongoDB with locations. Locations have an array of bands. And I want to add bands to this array. The backend seems to work fine, at least with Postman it works. But when I try to add a band through the frontend, I get a http 500 error.
This is the back end code:
app.put('/api/locations/:location', async (req, res) => {
let location = req.params.location;
let updatedlocation = req.body;
try {
await client.connect();
const database = client.db('Concerts');
const collection = database.collection('locations');
const query = { locationname: location };
const result = await collection.updateOne(query, { $set: updatedlocation });
if (result.matchedCount === 0) {
let responseBody = {
status: "No Location under the name " + location
}
res.status(404).send(responseBody);
}
else {
res.send({ status: "Location " + location + " has been updated." });
}
} catch (error) {
res.status(500).send({ error: error.message });
}})
This is the method in the frontend:
function addConcert() {
location.concerts.push(chosenband);
console.log("http://localhost:3001/api/locations/" +name);
console.log(location);
axios.put("http://localhost:3001/api/locations/" +name, location)
.then((response) => {
alert("Konzert wurde hinzugefĆ¼gt");
})
.catch((error) => {
alert("Nope");
console.log(error);
});
}
Info: the {chosenband} comes from a select. This seems to work as well, as the console logs show.
The object is correct and includes the new band:
this is the log from the browser
So the object seems fine. Also the put-url is correct.
But I always get this 500 error
Thankful for any advise!
Found the problem. I didn't instantiate the location correctly. First I instantiated it simply as
let location = {}
, that didn't work. When I instantiated it with all the attributes
let location = {example:"", second:""}
it worked. Thanks for your help

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'

NPM instagram-web-api checkpoint required

I have configured the NPM instagram-web-api package. I have instantiated the Instagram object and passed the correct credentials:
const Instagram = require('instagram-web-api');
const { igUsername, igPassword } = process.env
const ig = new Instagram({ username: igUsername, password: igPassword });
(async () => {
try {
await ig.login()
} catch (err) {
if (err.error && err.error.message === 'checkpoint_required') {
console.log(err.error);
const challengeUrl = err.error.checkpoint_url
await ig.updateChallenge({ challengeUrl, securityCode: 670381 })
}
}
const profile = await ig.getProfile()
})()
I am getting a 'checkpoint_required' error message and each time I start the server a Instagram verification code is sent to my email. I don't know where to enter that code or how to resolve this issue.
Having the same issue. I thing we need to call an extra api for the OTP validation in order to login.
Check this out - https://github.com/ohld/igbot/issues/630 for the solution or reference.

How can I verify token google recaptcha 3 on adonis js?

I using vue as my front end. I send token from my front end like this :
let payload = {
token: tokenCaptcha
}
axios.post(`http://127.0.0.1:3333/api/v1/category`, payload)
.then(response => {
return response.data
}).catch(
error => {
console.log(error)
})
The token will used to verify on the backend. My backend using adonis.js
The script of controller like this :
'use strict'
class CategoryController {
async store ({ request, response }) {
return request.input('token')
}
}
module.exports = CategoryController
My routes like this :
Route.group(()=>{
Route.post('category', 'CategoryController.store')
}).prefix('api/v1')
How can I verify the token on adonis.js(backend)?
I had search reference. But I don't find it
You need to use axios. Something like:
const axios = use('axios')
const Env = use('Env')
const querystring = use('querystring')
async store({ request, response }) {
const data = request.only(['token'])
try {
const data_request = await axios.post('https://www.google.com/recaptcha/api/siteverify', querystring.stringify({ secret: Env.get('RECAPTCHA_PRIVATE_KEY'), response: data['token'], remoteip: '172.217.23.110' }))
if (!data_request.data.success) {
//If the recaptcha check fails
...
}
} catch (error) {
...
}
}
Google documentation - Verifying the user's response
This code is made for v2. But the verification is the same : https://developers.google.com/recaptcha/docs/v3#site_verify_response