I'm trying to make http request in my react native app(in android in real device) with the localhost url.
after it failed in localhost url with the error
Network request Failed
I changed it to my ipv4 but it still not works.
but when I'm using in POSTMAN to check with my ipv4 it looks it works fine.
try {
let response = await fetch("http://myIPV4address:3008", {
method: method,
headers: headers,
body: body != null ? JSON.stringify(body) : null,
})
console.log('response:',response)
const endTime = (new Date()).getTime();
if( response.status == 401 ) {
return Promise.reject(response);
}
if( response.status == 400 ) {
return Promise.reject(response);
}
if( response.status == 404 ) {
return Promise.reject(response);
}
if( response.status == 500 ) {
return Promise.reject(response);
}
if( response.status == 502 ) {
return Promise.reject(response);
}
let responseJson = response.headers.map['content-type'][0].includes('application/json') ? await response.json() : response.statusText;
return responseJson;
} catch(error) {
console.error(error);
}
maybe it is settings in react native app I need to change?
Solution:
I connected to the wifi where the pc is connect because before it doesn't know what is localhost is
look for dns server the solution is to configure your emulator
Related
I want that when some XMLHttpRequest at 'https://myurl.com' be send, isntantly returns status code 200 and myOwnResponse at response body, I don't want that the request go to the server, the reason is that the server response is very slow, and I want to increase the performance.
I want something like tweak: mock and modify HTTP requests, how can I do that?
var _open = XMLHttpRequest.prototype.open;
window.XMLHttpRequest.prototype.open = function (method, URL) {
const myUrl = 'https://myurl.com'
if(method === 'GET' && URL === myUrl) {
const myOwnResponse = {'myResponse': true}
return myOwnResponse
} else {
return _open.apply(this, arguments);
}
};
I am working on a NextJS project and I want to use a github webhook to deploy a script that has deployment instructions.
I have setup a push webhook in github
I tried to add the following code in my server.ts file and for now testing this with ngrok
// testing
server.post("/webhooks/github", function(req, res) {
var sender = req.body.sender;
var branch = req.body.ref;
if (branch.indexOf("master") > -1 && sender.login === githubUsername) {
deploy(res);
}
});
function deploy(res: any) {
childProcess.exec("sh deploy.sh", function(err, stdout, stderr) {
if (err) {
console.error(err, stderr);
return res.send(500);
}
console.log(stdout);
res.send(200);
});
}
this file is my node file for the nextJS application
however I am getting a 502 in my ngrok logs
I would like to know where in my NextJS application should I put this webhook endpoint to get it to work
The only way I could get this to work is by creating another app on the same server ( I used express ) and then used an endpoint on that as github webhook and from there I ran the deploy script.
simple solution and hope this helps somebody..
I know this is late, but this worked for me:
// pages/api/webhooks/github.js
const { exec } = require("child_process");
const crypto = require("crypto");
// Handle GitHub Webhooks
export default function handler(req, res) {
try {
console.log("Incoming Request");
if (req.method !== 'POST') {
res.send(404);
return;
}
let sig =
"sha256=" +
crypto
.createHmac("sha256", process.env.WEBHOOKS_SECRET)
.update(JSON.stringify(req.body))
.digest("hex");
if (
req.headers["x-hub-signature-256"] === sig &&
req.body?.ref === "refs/heads/main" &&
process.env.REPO_PATH
) {
exec(
"cd " +
process.env.REPO_PATH +
" && git pull && npm install && npm run build && pm2 restart app"
);
console.log("GitHub Webhook ran successfully");
res.end();
return;
}
console.log("GitHub Webhook failed");
res.end();
return;
} catch (e) {
console.log(e);
}
};
I am trying to upload an array of images using form data and xhttp.
Client : React Native - Both platforms
Server : Node running on GCP
Images go into s3.
Problem : Images are uploaded into s3. And when i look at my server logs i see the server is sending 200.
But, client is always receiving response code 0.
And also xhttp goes from state 1 -> 4.
We have added CORS on both ends so that might not be an issue.
I have accept and content headers. But, no idea what's going wrong.
Any help is appreciated.
React-Native Client:
upload()
{
let url = "MYAPIGOESHERE"
let uploadBody = new FormData()
let imagesUpload = []
imagesUpload.push({type:'image/jpg',uri:this.state.coverImage[0].uri,name:"cover"})
uploadBody.append('photos',{uri:this.state.coverImage[0].uri, type:'image/jpg', name:"cover"})
uploadBody.append('duration',this.state.duration)
var xhttp = new XMLHttpRequest()
xhttp.onreadystatechange = function() {
console.log(this.readyState+" "+this.statusText)
if (this.readyState === 4) {
alert(this.status)
if (this.status === 200) {
console.log(this.responseText);
} else {
console.log(this);
}
}
if(this.readyState === 3)
{
console.log("Inside 3")
}
if(this.readyState === 2)
{
console.log("Inside 2")
}
};
xhttp.open("POST", url)
xhttp.setRequestHeader('Accept', 'application/json');
xhttp.setRequestHeader('Access-Control-Allow-Origin', '*');
xhttp.responseType = 'json'
xhttp.send(uploadBody)
}
I'm trying to capture http status codes in angular in service which calls a backend service, i'm facing issues as i see status 204 , but when logging angular show status null, here is what i'm doing in my service:
return this.http.get<JSON>(mybackendsserviceurl)
.do(res => {
})
.catch(res => {
return this.handleError(res);
});
}
private handleError(err: HttpErrorResponse) {
console.log(err.message);
return Observable.throw(err.message);
}
How to catch different errors from backend service, like 204,403,404,500...etc and display a user friendly message for each error?
my frontend is calling the service from API gateway and i'm setting the errors in Response Integrations.
To handle different status codes just check them:
this.http.get<JSON>(<URL>)
.subscribe(
res => console.log(res),
err => {
console.error(err);
this.handleError(err);
});
private handleError(err: HttpErrorResponse) {
if( err.status == 500 ) {
return Observable.throw(new Error(<YOUR USERFRIENDLY MESSAGE>));
} else if( err.status == 400 ) {
return Observable.throw(new Error(<YOUR MESSAGE>));
}
// you can also catch all errors of a group like this
else if( err.status < 500 && err.status >= 400 ) {
return Observable.throw(new Error(<CLIENT ERROR MESSAGE>));
}
}
In your UI you can handle the Observable and of course, show a nice dialog with the error message.
I am making a React Native function that pulls the HTML of a webpage. It works fine if the URL exists and I receive a 200 status code. However, when I put a wrong url in there (something that would receive a 404 error), it displays a red screen that says "Network request failed." I'd like to catch the error without the whole app halting and display an alert to the user. How can I go about doing that?
fetchEvents() {
fetch('http://www.wrongurl.com', {
method: 'GET',
redirect: 'follow'
})
.then(function(response) {
if (response.status == 200) {
let responseText = JSON.stringify(response.text());
console.log(responseText);
}
else throw new Error('HTTP response status not code 200 as expected.');
})
.catch(function(error) {
console.error(error);
return error;
});
}
This is how I solved this, making graceful errors that don't crash the app using promises:
In my API service class:
fetchEvents() {
let thisCurrentAPIService = this;
return new Promise(
function (resolve, reject) {
fetch('http://www.wrongurl.com');
.then(
function(response) {
if (response.ok) {
let responseText = JSON.stringify(response.text());
console.log(responseText);
}
else {
reject(new Error(`Unable to retrieve events.\nInvalid response received - (${response.status}).`));
}
}
)
.catch(
function(error) {
reject(new Error(`Unable to retrieve events.\n${error.message}`));
}
);
}
);
}
Then I call it from my React Component. If I receive an error, I create the alert there.
this.state.apiService.fetchEvents()
.then(
function (value) {
console.log('Contents: ' + value);
},
function (reason) {
Alert.alert(`${reason.message}`);
});
Hilarious, three years almost and no proper answer still.
However, console.error(error) is what actually causing the app to throw a red screen.
You can use Alert component from react-native.
fetchEvents() {
fetch('http://www.wrongurl.com', {
method: 'GET',
redirect: 'follow'
})
.then(function(response) {
if (response.status == 200) {
let responseText = JSON.stringify(response.text());
console.log(responseText);
}
else throw new Error('HTTP response status not code 200 as expected.');
})
.catch(function(error) {
Alert.alert(error); // Using this line
});
}
But I prefer using toast like on Android than alert.
console.warn('This is my error');
If this is simply for dev it might help. It explicitly uses the little warning toast to provide whatever feedback you need. Note: this is definitely not for production use.
Add following in app index.js file
console.reportErrorsAsExceptions = false;