I've came across the following error.
At the moment I developing an Android App with React Native therefore I'm planning to use fetch for doing a post request for me.
fetch("https://XXreachable-domainXX.de/api/test", {
method: "post",
body: JSON.stringify({
param: 'param',
param1: 'param',
})
})
.then((response) = > response.json())
.then((responseData) = > {
ToastAndroid.show(
"Response Body -> " + JSON.stringify(responseData.message), ToastAndroid.SHORT
)
})
.catch((error) = > {
console.warn(error);
});
The app now throws an error:
TypeError: Network request failed
When I change the code to a GET-Request it's working fine, in the browser with a window.alert() as a return it's cool and also the Chrome extension Postman returns data correctly.
Developing with Windows OS/PHP built-in server/react-native Android on device:
check server local IP address (ipconfig), e.g. 172.16.0.10
in react-native fetch use this URL and proper port (fetch('http://172.16.0.10:8000/api/foo))
run PHP built-in server with this specific IP instead of the localhost: php -S 172.16.0.10:8000 ...
turn off Windows firewall for the private networks
That fixed the connection problem between Android phone and the local server for me.
This React Native's error is rather useless, so you need to get the actual underlying error first. The most straightforward way is to write a small native program that would just perform the same query using HttpsURLConnection.
For me the actual error was java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
which has a well known solution: https://developer.android.com/training/articles/security-ssl.html#MissingCa
This is quite likely your case also, given that the browsers and Postman have no problem with the request. To check it run openssl s_client -connect XXreachable-domainXX.de:443 -showcerts. If there are certificate errors, fix them first, it could spare you time writing the native program.
Edit: actually the easiest way to see all underlying android errors for react native is simply running 'adb logcat' in terminal
None of the other answers helped me.
The problem was headers:
Old header:
fetch(API_HOST, {
method: 'POST',
headers: {
Accept: 'application/json'
},
body: JSON.stringify(data),
Updated header:
fetch(config.API_HOST, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json' // I added this line
},
body: JSON.stringify(data),
If you have had this error and you are sure everything works well and you are running an emulator, simply close your emulator and fire it up again.
It should run now.
This usually happens after you have hibernated your system for a while
step1>
add android:usesCleartextTraffic="true" line in AndroidManifest.xml like:
// add this line
...
step2>
Delete all debug folder from your android folder..
I had a major issue doing the same on the android emulator. On iOS approving the domain in the info.plist was necessary. To be clear I was attempting to login to my .NET web hosted API.
The fix was to make sure the post data was parameterised.( I'm pretty sure that's a word)
export const loginUser = ({ userName, password }) => {
const data = `UserName=${userName}&Password=${password}&grant_type=password`
return (dispatch) => {
dispatch({ type: LOGIN_USER })
fetch(URL_LOGIN, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: data
// body: {
// UserName: userName,
// Password: password,
// grant_type: 'password'
// }
})
.then((response) => {
loginUserSuccess(dispatch, response)
})
.catch((response) => {
loginUserFailed(dispatch, response)
})
};
};
If you run into this problem on emulator make sure you also test it on the device. It's most probably not happening there.
Just so you know there's nothing to worry about if you can work around it.
I had this problem on Android due to an expired certificate. The error message I had was com.android.org.bouncycastle.jce.exception.ExtCertPathValidatorException: Could not validate certificate: Certificate expired at Fri Sep 29 16:33:39 EDT 2017 (compared to Fri Dec 08 14:10:58 EST 2017).
I was able to confirm this using digicert.com.
Unfortunately I did have to dig rather deep into the React Native code and debug the XHR code in the bundle (index.android.bundle) in order to find the error message and the URL in question, because it was in some of my logging code, which I obviously didn't log to the console as well. :)
I was helped by this GitHub issue comment.
My issue was fixed when I restarted the emulator
I had same issue using the fetch,this is a type error.so try using Axios. This worked for me.
the code which wasnt working :error:[typeError : network Request failed]
return fetch(addProduceApi, { method: 'PATCH', body: bodyParamData, headers: getAuthHeader() })
.then((response: any) => response.json()) .catch((error: any) => console.log('Error in patchProduce: ', error));
the working code:
return axios.patch(addProduceApi,produceData,{ headers: getAuthHeader()})
.then((response: any) => response.json()) .catch((error: any) => console.log('Error in patchProduce: ', error));?
Check two cases bellow
Wrong end-point
Internet connection: both real-device, virtual-device
It has eaten 2 hour with the second reason.
Related
I've been stuck on this issue for some time now, I am trying to subscribe to Linkedin's webhook using ngrok for testing on localhost, and have been trying for some time now, i have tried using encode uri's as well but still running into error, I have verified that the APP_ID, profileId and organizationId i'm using are correct, but still i get the same error. I have also tried using the Restli protocol that linkedin suggests in their documentation but to no avail.
let url = `https://api.linkedin.com/v2/eventSubscriptions/(developerApplication:urn:li:developerApplication:${config.IN.APP_ID},user:urn:li:person:${profileId},entity:urn:li:organization:${organizationId},eventType:ORGANIZATION_SOCIAL_ACTION_NOTIFICATIONS)`;
return new Promise((resolve, reject) => {
request(
{
url,
method: 'PUT',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${accessToken}`,
// 'X-Restli-Protocol-Version': '2.0.0',
},
json: {
webhook: "https://url.ngrok.io/api/v1/webhook/linkedin/callback"
},
},
(err, response, body) => {
if (err) {
reject(err);
} else {
resolve(body);
}
},
);
});
I have been receiving this error constantly no matter what I try, I have tried sending the url like this:
https://api.linkedin.com/v2/eventSubscriptions/(developerApplication:urn:li:developerApplication:{${config.IN.APP_ID}},user:urn:li:person:{${profileId}},entity:urn:li:organization:{${organizationId}},eventType:ORGANIZATION_SOCIAL_ACTION_NOTIFICATIONS)
https://api.linkedin.com/v2/eventSubscriptions/${encodeURIComponent((developerApplication:urn:li:developerApplication:${config.IN.APP_ID},user:urn:li:person:${profileId},entity:urn:li:organization:${organizationId},eventType:ORGANIZATION_SOCIAL_ACTION_NOTIFICATIONS))
All I receive is this error
'{"serviceErrorCode":100,"message":"Unpermitted fields present in RESOURCE_KEY: Data Processing Exception while processing fields [/key]","status":403}'
Any help would be appreciated, I have been stuck on this for a while now.
The request seems to be OK , but the method should be GET (not PUT)
One thing is to check which ID are you using for application_id. The application ID is the one in the url - https://www.linkedin.com/developers/apps/<id from here>/settings
. You need to use and uncomment the header for Restli.
I'd say that your url needs to look like this, as this is from their original POSTMAN collection.
https://api.linkedin.com/v2/eventSubscriptions/(developerApplication:urn%3Ali%3AdeveloperApplication%3A{{application_id}},user:urn%3Ali%3Aperson%3A{{person_id}},entity:urn%3Ali%3Aorganization%3A{{organization_id}},eventType:ORGANIZATION_SOCIAL_ACTION_NOTIFICATIONS)
You can validate here, their full collection - https://www.postman.com/linkedin-developer-apis/workspace/e781b3ac-4101-4d60-8981-afcb4812623d/request/16069442-9d0bf046-ea81-4af0-9515-d07246a0ab39
LinkedIn webhooks does not support ngrok URIs
I am using the following code from react-native mobile application to make a social authentication call to dj-rest-auth local link. However I am always receiving an error. Please let me know what is the issue.
fetch(
"http://localhost:8000/dj-rest-auth/facebook/",
{
method: "POST",
headers: {
'Accept': 'application/json',
'Content-type':'application/json'
},
xsrfCookieName:"csrftoken",
xsrfHeaderName:'X-CSRFToken',
body:JSON.stringify({access_token : resolvedToken})
}
)
.then(resp => resp.json())
.then(data => {
console.log(data);
}
)
.catch(error => console.log(error))
Error Details:
Network request failed
at node_modules/whatwg-fetch/dist/fetch.umd.js:535:17 in setTimeout$argument_0
at [native code]:null in callFunctionReturnFlushedQueue
Alternate Error Update:
If I use axios for the API request instead of fetch i.e. await axios.post instead of fetch, then i am getting the following error:
Network Error
at node_modules/axios/lib/core/createError.js:16:14 in createError
at node_modules/axios/lib/adapters/xhr.js:84:24 in handleError
at node_modules/react-native/Libraries/Network/XMLHttpRequest.js:600:10 in setReadyState
at node_modules/react-native/Libraries/Network/XMLHttpRequest.js:395:6 in __didCompleteResponse
at node_modules/react-native/Libraries/vendor/emitter/EventEmitter.js:189:10 in emit
at [native code]:null in callFunctionReturnFlushedQueue
the problem was that it cannot find resolvedToken Variable. so I have added on top of the code, and it works well.
var resolvedToken = "2222";
fetch(
"http://localhost:8000/dj-rest-auth/facebook/", {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-type': 'application/json'
},
xsrfCookieName: "csrftoken",
xsrfHeaderName: 'X-CSRF-Token',
body: JSON.stringify({
access_token: resolvedToken
})
}
)
.then(resp => resp.json())
.then(data => {
console.log(data);
})
.catch(error => console.log(error))
The error was being faced due to the usage of localhost address for django local server call here. The issue remains for localhost or 127.0.0.1 as well.
Also, next I tried using mobile hotspot with my laptop and then used the currently assigned IP address of my laptop's Wi-Fi, to run django server and place API call to it. This doesn't work if using mobile hotspot and same error is faced.
However upon using a LAN router and then using the assigned local Wi-Fi IP address of the laptop, the issue was resolved.
This has now created new issue though. The API call succeeds and i receive the token only upon the first API call or first run. Thereafter I receive the error of missing or invalid csrf token.
However since that is a new issue and is different from this question, I am currently closing this question. If I am unable to resolve the new issue, I may ask a new question.
I have a login page in my REACT website sending a POST request with fetch, but every time the request is submitted for some reason it refreshes the page and send it as a GET request, here's the method on my login page:
onSubmitSignIn = () => {
fetch("http://192.168.56.1:8560/signin", {
type: 'POST',
headers: {'Accept': 'application/json',
'Content-Type': 'application/json'},
body: JSON.stringify({
email: this.state.signinEmail,
password: this.state.signinPassword,
}),
})
.then(response => response.json())
.then(data => {
if (data ==='success'){
}
})
}
the server side signing page is as follows:
app.post('/signin', (req, res) => {
if (req.body.email === database.users[0].email && req.body.password === database.users[0].password){
res.json("success");
}else{
res.status(404).json("Error loggingin");
}
})
It's working fine with Postman, the server seems to be ok.
I have tried changing HTTP to https even though my server is HTTP just in case.
Tried restarting both servers, tried changing to fetch to axios but nothing seems to be working.
Any thoughts?
onSubmitSignIn = (event) => {
event.preventDefault() // <= You Need this
fetch("http://192.168.56.1:8560/signin", {
type: 'POST',
headers: {'Accept': 'application/json',
'Content-Type': 'application/json'},
body: JSON.stringify({
email: this.state.signinEmail,
password: this.state.signinPassword,
}),
})
.then(response => response.json())
.then(data => {
if (data ==='success'){
}
})
}
Create-React-App Proxying API Requests in Development -- src/setupProxy.js
People often serve the front-end React app from the same host and port as their backend implementation.
Such setup is not required. However, if you do have a setup like this, it is convenient to write requests like fetch('/api/todos') without worrying about redirecting them to another host or port during development.
To tell the development server to proxy any unknown requests to your API server in development, add a proxy field to your package.json, for example:
"proxy": "http://localhost:8560",
Configuring the Proxy Manually
First, install http-proxy-middleware using npm or Yarn:
$ npm install http-proxy-middleware --save
$ # or
$ yarn add http-proxy-middleware
Next, create src/setupProxy.js and place the following contents in it:
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function(app) {
app.use(
'/api',
createProxyMiddleware({
target: 'http://localhost:8560',
changeOrigin: true,
})
);
};
API:
https://create-react-app.dev/docs/proxying-api-requests-in-development/
I'm just replying in case anybody has got the same issue as I was having, after a couple of sleepless nights digging through my code, I figure the template for my login page was taken from a "tachyon" template, what I missed, somewhere in my version control, was a "form" that was actually supposed to be turned into a "div", after going through this question here why-the-post-request-becomes-a-get-request it hit me, basically, if you happen to be taking the information from inside of a "form" and this form does not have a method post, it will automatically turn the API request into a GET request and fill up the URL with the information.
So that is sorted. Now let us tackle the rest of the bugs.
I am writing an app in React-Native that makes a request to the Hubspot API. This has given me issues, as I initially attempted to make the request using the Node JS request module, which does not work with React Native when using Expo. I am now attempting to make the request to the Hubspot API with React Native's own Fetch API, but am having trouble translating my initial code written using the Node JS request module. I get an error when making a request to the Hubspot API. I've attached the two versions of the code to this question. Could anyone explain what is wrong with my translation of the Node JS code? Any advice would be much appreciated. Node JS version (request succeeds)
Fetch version (request fails)
Welcome to Stack Overflow :)
I think your fetch request is not written correctly. Instead of creating a new Request const you could pass all your params to the fetch function directly:
fetch('https://hubapi.com/whatever/CONFIDENTIAL', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
properties
})
})
.catch((error) => {
console.error(error);
});
Notice I also added a catch block at the end of the request. If it still fails you should at least get a better understanding of what exactly is failing.
The code I quoted above is taken from the React Native docs, link here. The docs contain a lot of great examples, including using a async/await and other networking libraries.
I tested it for you in my react native project. The request succeeds, of course I get This hapikey (CONFIDENTIAL) doesn't exist as response, because I don't have a key, but the query runs successfully:
try {
const response = await fetch(
'https://api.hubapi.com/contacts/v1/contact/?hapikey=CONFIDENTIAL',
{
method: 'POST',
headers: new Headers({ 'Content-Type': 'application/json' }),
body: JSON.stringify({
"properties": [
{ property: 'email', value: 'test#email.com' },
{ property: 'firstname', value: 'Sean' },
{ property: 'lastname', value: 'Smith' },
]
})
}
);
const responseJson = await response.json();
console.log("response from hubapi:", responseJson)
} catch (e) {
console.error("Error on fetch request:", e);
}
I'm writing a React Native app to run on Android phone. In the app, I'll fetch data from a .NET web service on the local network (using port 8085).
When I test the app on emulator, the fetch run as expected. But when I run it on my phone, the fetch always fail with error Network request failed (the server and the phone is on the same LAN).
I've try to change the port to 80, and the app run as expected on my phone.
I also turn off all others website in IIS, but the same problem with port <> 80.
I've do some research on Google (many time it redirect me to SO and Github) but with no luck.
Below is my fetch:
_getValue1 = async () => {
try {
const response = await fetch('http://192.168.1.165:8085/index.aspx/GetValue1', {
body: JSON.stringify({ Usr: ... }),
headers: {
'accept': 'application/json; charset=utf-8',
'content-type': 'application/json; charset=utf-8',
},
method: 'POST',
});
const json = await response.json();
// do things with the json result
}
catch (err) {
// always go here if run on real phone with url port other than 80
}
}
Anyone has experience with this problem please help, thanks in advance.