I am currently working on a React Native project.
My code is this:
const onSubmit = async ({email, password}) => {
const url = 'https://gravitee.****.com:***/***/api/auth/signin';
try {
const response = await axios.post(url, {
email,
password,
registrationSource: SOURCE,
});
console.warn(response);
} catch (error) {
console.warn('err: ', error);
}
};
I have made this project on React as well and this is working well there. But on React Native it gives me Network Error. Nothing else. I tried with fetch api, it didn't work either. And what's interesting is I can fetch data from an external api that I just found on web. So what could be the problem? By the way i am running app on ios simulator and my device is Mac M1
Full error is like this:
err: AxiosError: Network Error
Call Stack
onSubmit
index.js: 87:7
asyncGeneratorStep
asyncToGenerator.js: 3:16
\_throw
asyncToGenerator.js: 29:27
tryCallOne
internalBytecode.js: 53:16
anonymous
internalBytecode.js: 139:27
I tried sending request to gravitee with axios and fetch and expecting login data of the user.
Related
I have an api used for login in my react native app. The api is implemented and working as its supposed to. But the issue is that if the user enters wrong email or password m not receiving the error message in the response in the application. While if i test the api manually in postman it returns the error message required. i tried making a transformer for the error response but m not knowing how to implement it or use it. I'm using fetch to call my apis.
return fetch(fullUrl, requestParameters)
.then((response) => {
if(response.ok) {
return response.headers.get("content-type") === "application/json" ? response.json() : null
} else {
errorrr = ErrorTransformer.backward(response)
console.log("Error: ", errorrr)
}
And below is the tranformer made for the error response
import {createTransformer} from './Transformer';
const ErrorTransform ={
o:[
['message','message'],
['code','code'],
]
}
export default createTransformer(ErrorTransform)
And below is the response returned from postman when wrong info are entered
{
"message": "error",
"code": 1
}
You can check on the basis of the response code. I'll suggest using the Axios library. Axios NPM
After a lot of trials, i figured that the postman response when the user enters wrong email or password is a regular response object, it’s not an error. So its handling should be like a regular response. But what remained as an obstacle is to tell apart when i have a success response with the info returned, or when i have the error object returned. I solved this issue by combining the error transformer with the login transformer, and its handling it perfectly.
I am working on a user registration page in my group project and came across a bad request error when submitting the data. I created a button to get users so I can check the authentication and it gave me a 401. "HTTP401: DENIED - The requested resource requires user authentication. (Fetch)GET - http://localhost:49967/Users" When I login, I use the admin login that's in the database and I see a token in my developers options. How do I find this error? I am new to react and programming so if you can lend some advice or docs it would be appreciated.
So to test my api endpoint, I loaded Postman and attempted to GET/POST and everything worked. I am using a react front-end, SQL sever for the database and ASP.Net Core in Visual Studios c#.
For starters here is the const I am using to access the back end
const apiHelper = {
get(url, params){
return fetch(`${baseUrl}${url}`, {
headers: this.headers
})
.then(response => response.json())
.catch(error => {
console.log(error);
return Promise.resolve();
});
}
This is the onclick action
handleGetUsers = async() => {
const response = await apiHelper.get('Users')
if(response){
console.log(response)
}
}
Lastly my URL
http://localhost:49967/
I send an image file to my node server via my react app -
I want to host these images on google cloud or similar so they have an accessible URL.
I have tried using cloudinary and google cloud but to no avail thus far!
My react-side code (shortened):
imageFile = this.state.files[0])
const formData = new FormData()
formData.append('file', imageFile);
sendImage(formData)
sendImage(image) {
axios.post("https://137a6167.ngrok.io/image-upload", image, {
})
.then(res => { // then print response status
console.log(res.statusText)
})
}
The file is successfully sent to my server and consoled:
app.post('/image-upload', (req, res) => {
console.log('consoling the req.body!!!!' + JSON.stringify(req.body))
})
THE CONSOLE: consoling the req.body!!!!{"1":"[object File]"}
I did try use this following cloudinary method, yet it threw errors:
cloudinary.config({
cloud_name: process.env.CLOUD_NAME,
api_key: process.env.API_KEY,
api_secret: process.env.API_SECRET
})
app.use(formData.parse())
app.post('/image-upload', (req, res) => {
const values = Object.values(req.files)
const promises = values.map(image => cloudinary.uploader.upload(image.path))
Promise
.all(promises)
.then(results => res.json(results))
})
this gave me the error that an unhandled error in the promise wasnt handled and i got a bit lost with where to go beyond that!
I looked at google cloud storage too but couldn't get it working! Any advice?
What I really want to do is return back to my react app the URL of the hosted image - so it can be stored in DB for the user!
If you can help at all that would be greatly appreciated, thank you.
There are couple of things you need to fix on the front end before you try to upload to any cloud.
First you need to set 'Content-Type': 'multipart/form-data' header in axios to send the file data properly.
Check this thread for more details: How do I set multipart in axios with react?
Then on the express side you need multer or some other similar library to receive the data. You can't access it from req.body. multer adds req.files for example.
https://github.com/expressjs/multer
Try there steps and then post the exact error message you are receiving from google cloud.
In my react native app, the server is specified by the user. Although I put some control on the "url" field, sometimes the user put an url which simply does not exist.
Then, I got a TypeError:
Network request failed
How can I handle these case in my code?
Thank you
You should handle the error case in .then for fetch API.
For example:
fetch('...URL')
.then(
(response) => {
console.log('success',response)
},
(err) => {
console.log('error',err)
}
);
My frontend, using apollo-client, throws an exception when the backend returns an error after a request.
When the node server receives a request, I check the validity of the request's token using koa middleware. If the token is valid, the request is forwarded to the next middleware. If the token is invalid, I want to return a 401 access denied error to the client. To do this, I followed Koa's error documentation located here.
The code for the error handling middleware I wrote:
function userIdentifier() {
return async (ctx, next) => {
const token = ctx.request.headers.authorization
try {
const payload = checkToken(token)
ctx.user = {
id: payload.userId,
exp: payload.exp,
iat: payload.iat,
}
} catch (error) {
ctx.user = undefined
ctx.throw(401, "access_denied")
// throw new Error("access_denied")
}
await next()
}
}
This seemingly works on the backend, but not on the frontend. When the frontend receives this error, a JavaScript runtime error occurs. I am not sure what causes this.
Note, the unexpected "a" is the same "a" found in ctx.throw(401, "access_denied"). If it were instead ctx.throw(401, "x") the frontend shows "unexpected token x" instead.
The frontend code where the errors happens:
In an attempt to fix this, I followed Apollo's error handling documentation and used apollo-link-error.
const errorLink = onError(props => {
const { graphQLErrors, networkError } = props
console.log("ON ERROR", props)
if (graphQLErrors)
graphQLErrors.map(({ message, locations, path }) =>
console.log(
`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`
)
)
if (networkError) console.log(`[Network error]: ${networkError}`)
})
Then I combine all links and create the Apollo client like this:
const link = ApolloLink.from([errorLink, authLink, httpLink])
export const client = new ApolloClient({
link,
cache: new InMemoryCache(),
})
The output of the debugging log in apollo-link-error is as follows:
Related Documents
Someone seems to be having an identical error, but a solution was not listed.
I found that the errors were handled correctly on the frontend when I began using this library on the backend: https://github.com/jeffijoe/koa-respond
Using just ctx.unauthenticated()
But I would still like to know more about how to return json/object-based errors with koa without a plugin helping