FETCH/AXIOS DELETE not working with json-server - javascript

I know this problem is repeated, but I cannot find the answer to it.
My problem is similar to this one:
Proper Fetch call for Delete using json-server?
I also used fetch and axios both like this:
await axios({
method: 'DELETE',
url: `http://localhost:8000/${measurementData.toolType}?LesionNamingNumber=${measurementData.lesionNamingNumber}`
});
await fetch(`http://localhost:8000/${measurementData.toolType}?lesionNamingNumber=${measurementData.lesionNamingNumber}`, {
method: 'DELETE'
}).then(data => {
console.log('data deleted');
});
I am still getting this error 'DELETE http://localhost:8000/EllipticalRoi?lesionNamingNumber=1 404 (Not Found)'. But I can see the data after visiting this URL.
My react is running on localhost:3000
I am using JSON-server with react.
JSON-SERVER version - 0.16.3
Any suggestions for this problem.

Related

Axios POST to endpoint, returns OPTIONS request

I am trying to make a post request from a form to an endpoint, the form works fine, and the db too. The main issue is that i am posting to this endpoind localhost:3001/professional with the body of the form as data
export const postPro = (data) => async () =>{
console.log(data)
axios({
method: 'post',
url: "http://localhost:3001/professional",
data: data
})
}
data itself is an object. This is what i get from the console after i press send:
console of backend returning options, I did the first 2 post with postman to see if it works the db, and indeed it does.
I am using Redux toolkits(first time i use it) and React Native
I try rewriting the post, like this:
axios.post("http://localhost:3001/professional", data)
then i try to console.log the data to see if reaches the axios.post and it does, i can see the log of the object data in the console.
Also i was thinking that has something to do with async await so i try to play with that a little, and it's the same result.

Linkedin webhooks event subscription not working

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

Translating Node JS request to an API to React Fetch syntax

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);
}

Put works in Postman but not AXIOS

This is the weirdest thing in my MERN app. When I do a PUT from Postman to my api it works and updates my api and mongoDB. On the front-end it doesn't update the api even though console logs are showing the correct values and the url is the same? Any help or direction would be appreciated... been playing with it for days now.
POSTMAN PROOF UPDATES WORK
The code for my axios is as follows:
handlePlayerSubmit(id, player) {
console.log('This is the id: ' + id);
console.log('This is the player: ' + player);
let apiUrl = 'http://localhost:3001/api/teams';
//sends the id and new author/text to our api
axios.put(`${apiUrl}/${id}`, player).catch(err => {
console.log(err);
});
}
So I know it's firing due to the console logs... not sure why its not updating the api?
Also it's not console.logging an error.
NETWORK SCREEN SHOT IN DEV TOOLS
HEADERS FROM NETWORK TAB:
This is happening because Axios serializes JavaScript objects to JSON. To serialize in application/x-www-form-urlencoded format you will need to use one of the techniques described in the Axios documentation.
I think qs is a nice solution for you:
let apiUrl = 'http://localhost:3001/api/teams';
//sends the id and new author/text to our api
axios.put(`${apiUrl}/${id}`, qs.stringify(player)).catch(err => {
console.log(err);
});
Axios doesn't like posting plain objects.
One way to workaround issue is with FormData:
let formData = new FormData();
formData.append('param1', 'hi');
formData.append('param2', 'hello');
axios({
method: 'POST',
url: '/api/some-endpoint/',
data: formData
}).then(response => {
console.log(response);
});
https://github.com/axios/axios/issues/1195

React Native Post Request via Fetch throws Network Request Failed

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.

Categories

Resources