axios Post returning error in react native - 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

Related

I only get an exception and not the error message from the server

I am currently programming a small login api and have implemented it with my react native project using axios request. But i have a problem now my server send an error status code with a message but in the react antive app it only comes to an exception with the status code and not with the message. How can I best solve this do I have to take the status code out of the server and just send text back or is there another solution?
My React Native api.js:
import axios from "axios";
import AsyncStorage from "#react-native-community/async-storage";
const instance = axios.create({
baseURL: "http://example.com",
});
instance.interceptors.request.use(
async (config) => {
const token = await AsyncStorage.getItem("token");
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
(err) => {
return Promise.reject(err);
}
);
export default instance;
My React Native api trigger:
const Signup = async ({email, password}) => {
try{
const response = await myApi.post("/api/signup", { email, password });
if (response.data.token){
navigation.navigate('setup');
}else{
setError(response.data);
}
}catch (err){
console.log(err);
setError('Internet Error');
}
}
and my server response
return res.status(400).send({
message: "Email or password incorrect!",
});

laravel react native axios post

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

Call Nextjs API from within Netlify function

I got a serverless Netlify function like this:
exports.handler = async function(event, context) {
return {
statusCode: 200,
body: JSON.stringify({message: "Hello World"})
};
}
When called by this url <site-name>/.netlify/functions/helloworld
I do get the message {"message":"Hello World"}
I also got a pages/api/mailingList.js Nextjs API endpoint:
const axios = require('axios');
export default async function handler(req, res) {
//console.log(req.query.mail);
if (req.method === "PUT") {
axios
.put(
"https://api.sendgrid.com/v3/marketing/contacts",
{
contacts: [{ email: `${req.query.mail}` }],
list_ids: [process.env.SENDGRID_MAILING_LIST_ID],
},
{
headers: {
"content-type": "application/json",
Authorization: `Bearer ${process.env.SENDGRID_API_KEY}`,
},
}
)
.then((result) => {
res.status(200).send({
message:
"Your email has been successfully added to the mailing list. Welcome 👋",
});
})
.catch((err) => {
res.status(500).send({
message:
"Oups, there was a problem with your subscription, please try again or contact us",
});
console.error(err);
});
}
}
This mailing list API endpoint, do work when using curl from the terminal with PUT as the method:
curl -X PUT -d mail=helloworld#gmail.com https://netlify.app/api/mailingList
The API endpoint also work from the URL (/api/mailingList?mail=helloworld#gmail.com) when removing the if (req.method === "PUT") { part from the mailingList.js
However, I am NOT able to get the API endpoint to be called from within the Netlify function.
(Preferably the mailingList API should be possible to call multiple times with different mailing list IDs from the Netlify function helloworld.js based on different logic /api/mailingList?mail=helloworld#gmail.com&listid=xxx)
To get the API endpoint to be called at all, from the function, I have tried adding a axios call from the helloworld.js to mailingList.js like this
const axios = require('axios');
exports.handler = async function(event, context) {
const mail = "helloworld#gmail.com";
// add to mailinglist
axios
.put("/api/mailingList?mail="+mail)
.then((result) => {
if (result.status === 200) {
toast.success(result.data.message);
}
})
.catch((err) => {
console.log(err);
});
}
This result in the following error from the browser: error decoding lambda response: invalid status code returned from lambda: 0
(I do not get any error msg from the Netlify log, either helloworld.js or mailingList.js)
Clearly, there is something wrong with how I call the mailigList.js from helloworld.js. Would greatly appreciate if some one could give me some advice and show me what I am doing wrong.
How can I call the API endpoint (mailigList.js) from within the Netlify function helloworld.js? (Preferably multiple times with different mailing list IDs: /api/mailingList?mail=helloworld#gmail.com&listid=xxx)
Found the solution in this article: https://travishorn.com/netlify-lambda-functions-from-scratch-1186f61c659e
const axios = require('axios');
const mail = "helloworld#gmail.com";
exports.handler = (event, context, callback) => {
axios.put("https://<domain>.netlify.app/api/mailingList?mail="+mail)
.then((res) => {
callback(null, {
statusCode: 200,
body: res.data.title,
});
})
.catch((err) => {
callback(err);
});
};

sending back api data to vue in express returns empty object

I'm trying to send some data back from my express app using the following in my app.js this data comes from a 3rd party api and I want to send it back to my front end application. I am able to see the content in my express api but it doesn't seem to deliver a result to my front end?? anyone have any ideas as to why I'm getting log below in the console.
I suspect it has to do with some async or timeout issue with the express app but I haven't been able to fix the issue myself.
function getFish(){
axios.get('https://www.fishwatch.gov/api/species')
.then(function (response) {
console.log(response)
return response
})
.catch(function (error) {
console.log(error);
})
}
app.get('/getFish', async(req,res) =>{
let fish = await getFish()
res.json({fishes: fish})
})
when I try to log the data in my app, I only get an empty object
{}
here is my vue code to log the value's returned by my express api.
created:function(){
this.fetchFish()
},
methods: {
fetchFish(){
fetch('http://localhost:3000/getFish')
.then((response) => {
return response.json();
})
.then((data) => {
console.log(data);
});
}
}
You need to return the axios promise in your server's getFish function or the /getFish route won't be awaiting anything:
function getFish(){
// New `return` statement
return axios.get('https://www.fishwatch.gov/api/species')
.then(function (response) {
console.log(response)
return response
})
.catch(function (error) {
console.log(error);
})
}

React-native axios with ColdFusion component

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)