fetch on react component method with problem - javascript

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.

Related

POST request generates failed to fetch

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.

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

Login attempt with Fetch API failed

I am trying to build a web scraper using the Fetch API but the code below that I have written will always say that I need to put password and username, Did I do anything wrong?
fetch('http://quotes.toscrape.com/login', {
method: 'POST',
headers: {
"Content-Type": "application/json",
Accept: "application/json"
},
body: JSON.stringify({username:"myusername", password:"mysecretpassword"}),
})
.then(response => {
return response.text()
})
.then(html => {
console.log(html)
})
Problem solved,
I only needed to change the body with params whose value is
const params = new URLSearchParams();
params.append('username', 'usersname123')
params.append('password', 'userspassword123')

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

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