POST request generates failed to fetch - javascript

I'm having problems making a POST request through the fetch API from javascript and I get the following error: TypeError: Failed to fetch at fetchCallImpp at window.fetch
The code is the following:
const agregarCafetalDB = (nombre) => {
const data = {
"nombre": `${nombre}`,
};
const requestOptions = {
method: 'POST',
body: JSON.stringify(data),
redirect: 'follow',
mode: 'cors',
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
};
fetch(url, requestOptions)
.then(response => response.json())
.then(result => console.log(result))
.catch(error => console.log('error', error));
}
btnAgregar.addEventListener('click', (e) => {
agregarCafetalDB(cafetal.value)
});
I would like you to help me solve the error thank you very much in advance

Does the same error shows in other browsers? fetch is ES6 Javascript, maybe the browser you are using doesn't support it.
fetch(url, requestOptions)
Also, make sure that variable 'url' is defined.

Related

Creating and fetching authtoken with javascript from Django Rest Framework

http POST http://localhost:8000/api-auth-token/ username="saadman" password="Sakib123#"
It works fine when i run it on terminal.
Now, I am trying to implement equivalent code in javascript to fetch authtoken:
fetch('http://localhost:8000/api-auth-token/',{
method:'POST',
header:{
username: 'saadman'
password: 'Sakib123#'
}
}
But it's not working
finally this worked for me:
var raw = JSON.stringify({"username":"saadman","password":"Sakib123#"});
var requestOptions = {
method: 'POST',
headers: {"Content-Type": "application/json"},
body: raw,
redirect: 'follow'
};
fetch("http://192.168.43.189:8000/api-auth-token/", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));

fetch method JavaScript

I am working on a website and I am trying to write a script which sends data once someone creates an account. But I get some errors(attached a screenshot) and can't find a way to fix them as I'm still an intern. Hopefully someone can help me.
Thank you.
if (val2 == 1) {
fetch(hookURL, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
body: attrString,
mode: 'no-cors'
})
.then((response) => {
//console.log('hook returned, response= ', response);
});
enter image description here
If You want to send data - use a different method ;)
Try POST instead of GET
Look at the below example from:
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
const data = { username: 'example' };
fetch('https://example.com/profile', {
method: 'POST', // or 'PUT'
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
.then(response => response.json())
.then(data => {
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
});

Calling Api post method on button click in React

I have an event like below:
handleDownload(e) {
e.preventDefault();
alert('Hi');
let communityName = this.state['selectedCommunity'];
let files = this.state[files];
fetch(clientConfiguration['filesApi.local'], {
method: 'POST',
headers: new Headers(),
body: JSON.stringify({ communityName: communityName, body: files })
}).then((res) => res.json())
.then((data) => console.log(data))
.catch((err) => console.log(err))
};
I have a button as below:
renderDownloadButton() {
if (this.state.files && this.state.files.filter(i => i.checked).length) {
return (
<button id="download" styles="display: none;" onClick={this.handleDownload} >
Download
</button>
);
}
};
It fires but it is giving following error, any help please - thank you. At
let communityName = this.state['selectedCommunity'];
its giving me the error;
Can not read property state undefined
Any help please?
My guess is that you need to bind your handler, but it's really hard to tell without whole component code.
handleDownload = (e) => {
e.preventDefault();
alert('Hi');
let communityName = this.state['selectedCommunity'];
let files = this.state[files];
fetch(clientConfiguration['filesApi.local'], {
method: 'POST',
headers: new Headers(),
body: JSON.stringify({ communityName: communityName, body: files })
}).then((res) => res.json())
.then((data) => console.log(data))
.catch((err) => console.log(err))
}
For the api post not fetching the error can be one possible case of CORS error that browser do not allow you to access other network(private and secured IP address) so you need to actually allow the proxy setting as I can see your post data don't have any proxy enabled. Here is the code I am attaching
This is the pseudo code please make changes accordingly in your fetch method:
var targetUrl ='/downloadableReport'
const res= fetch(targetUrl,{
method: 'POST',
headers: {
'Content-Type': "application/json; charset=utf-8",
},
body: JSON.stringify({
"requestData":{
"userName":"XXX",
"password":"XXXX",
"clientId":"XXXX",
"txnType":"XXXX"
}
})
})
.then(response => response.json())
.catch(error =>{
console.log(error)
})
Also, you need to add setupProxy.js file (mind the name of the file should be this only) and add this code (with preferred changes)
const proxy = require("http-proxy-middleware");
module.exports = function(app) {
app.use(
proxy("/downloadableReport",{
target:"http://192.168.1.220:8080/report/abc" ,
changeOrigin:true
})
)
};

fetch on react component method with problem

Im trying to make an API CALL using fetch in a method (saveUser). API is working fine and de method is doing his work well but I dont know why the PUT doesnt work.
Here is the code:
saveUser(user: IUser) {
user = this.state.user;
let userId = user._id;
let url = `http://localhost:4200/api/update-user/${userId}`;
fetch(url, {
method: 'put',
body: JSON.stringify(user),
headers: {
'Content-Type': 'application/json'
}
}).then(res => res.json())
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', response));
debugger;
};
Here is all the code: manageUserPage
Make changes in your request like this:
fetch(url, {
method: 'PUT',
body: JSON.stringify(user),
headers: {
'Content-Type': 'application/json'
}
Let me know if the issue still persists and make sure you have enabled CORS.

React Native "fetch" returning server response without the information

I am using react native to create an application to act as a website that currently exists (with a user interface that works on a phone). i am using the "fetch" method to send a Http POST request to get information from a web server. The web server sends a response but it doesn't include the response message:
I apologies that is an image but the debugger is not working for me.
The code used to send the request:
HttpRequest = (RequestURL, callback) => {
var AdminLoginBindingModel = {
usr: this.state.username,
pwd: this.state.password,
}
fetch(RequestURL,
{
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(AdminLoginBindingModel)
})
.then((res) => {
callback(res);
})
.catch((error) => {
this.setState({Response: "Error: " + error});
})
}
The callback function in the parameters is just a function to change the state variable to display the information on the screen
ValidateResponse(response){
this.setState({Response: "Result: " + JSON.stringify(response),
displayMessage: "Success"});
console.log(JSON.stringify(response));
}
The Request being sent is "https://mibase-test.mibase.com.au/members/api/startSession.php?usr=&pwd="
The server responds with a json object regardless of a correct login or not
Edit:
Changing the response to
.then((res) => {
callback(res.json());
})
Result:
To get object from fetch response, you have to call res.json like following:
fetch(RequestURL, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(AdminLoginBindingModel)
})
.then(res => res.json()) // HERE
.then(obj => callback(obj))
But it occurs an error because response body itself is invalid json format. It contains some HTML tags:
{"member": {"username":"","password":"","key":"***","status":"No"}}<br><br>Username: <br>Key: ***
Please check the inplementation of server.
EDIT: full code here
const fetch = require("node-fetch")
HttpRequest = (RequestURL, callback) => {
const AdminLoginBindingModel = { usr: "foo", pwd: "bar" }
fetch(RequestURL, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(AdminLoginBindingModel)
})
.then(res => res.json())
.then(obj => callback(obj))
.catch(error => console.log(error))
}
const ValidateResponse = response => console.log(JSON.stringify(response))
URL = 'https://mibase-test.mibase.com.au/members/api/startSession.php?usr=&pwd='
HttpRequest(URL, ValidateResponse)
response doesn't contain received data directly. It provides interface methods to retrieve it. For example use response.json() to parse response text as JSON. It will return promise that resolves to the parsed object. You won't need to call JSON.parse on it:
fetch(RequestURL,
{
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(AdminLoginBindingModel)
})
.then((res) => {
return res.json();
}).then((obj) => {
console.log(obj);
});
Check https://developer.mozilla.org/en-US/docs/Web/API/Response and https://facebook.github.io/react-native/docs/network.html for more information.

Categories

Resources