Fetch with Post method in React-Native - javascript

I'm trying to do a fetch with the post method in my react-native, but I receive always an error:
TypeError: Network request failed
at XMLHttpRequest.xhr.onerror (whatwg-fetch.js:504)
at XMLHttpRequest.dispatchEvent (event-target.js:172)
at XMLHttpRequest.setReadyState (XMLHttpRequest.js:580)
at XMLHttpRequest.__didCompleteResponse (XMLHttpRequest.js:394)
at XMLHttpRequest.js:507
at RCTDeviceEventEmitter.emit (EventEmitter.js:181)
at MessageQueue.__callFunction (MessageQueue.js:366)
at MessageQueue.js:106
at MessageQueue.__guard (MessageQueue.js:314)
at MessageQueue.callFunctionReturnFlushedQueue (MessageQueue.js:105)
User creationg page
static createUser(Identity, FirstName, LastName, FiscalCode , Email) {
let formdata = new FormData();
formdata.append('Identity', JSON.stringify(Identity));
formdata.append('FirstName', (FirstName));
formdata.append('LastName', LastName);
formdata.append('FiscalCode', FiscalCode);
formdata.append('Email', Email);
return new Promise((resolve, reject)=> {
fetch('https://linktomyapi.com' , {
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data',
},
body: formdata
})
.then((response) => response.json())
.then((responseData) => {
if(responseData.Error){
Alert.alert("Errore");
}
global.utente = responseData;
resolve(responseData)
})
.catch((err) => {reject(err)})
})
}
About Identity, I take in this way:
let Identity =
{
AppName:
{
Username: this.state.FiscalCode,
Password: this.state.Password
}
}
I follow many guides about this argoument, but I don't understand why I receive these errors.

Can you try the following?
let params = {
Identity: JSON.stringify(Identity),
FirstName: FirstName,
LastName: LastName,
FiscalCode: FiscalCode,
Email: Email
}
return new Promise((resolve, reject)=> {
fetch('https://linktomyapi.com' , {
method: 'POST',
headers: {
"Content-Type": "application/json",
},
...(params && { body: JSON.stringify(params) })
})
.then((response) => response.json())
.then((responseData) => {
if(responseData.Error){
Alert.alert("Errore");
}
global.utente = responseData;
resolve(responseData)
})
.catch((err) => {reject(err)})
})
Are sure your content type is formdata?

The problem is there:
return new Promise((resolve, reject)=> {
fetch('https://linktomyapi.com' , {
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data',
},
body: formdata
})
In the fetch I pass the link as a string.
So the correct form is:
return new Promise((resolve, reject)=> {
fetch(https://linktomyapi.com , {
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data',
},
body: formdata
})

Related

Response data returns undefined from asp.net web api to vue.js

currently I'm fetching data from my api to front-end. I checked and my request body is arriving to server side. But after doing things when it comes to returning the token it always returns undefined data to vue.js:
[HttpPost("login")]
public async Task<IActionResult> Login([FromBody]User user)
{
var result = await _accountRepository.LoginAsync(user.username, user.password);
if (string.IsNullOrEmpty(result))
{
return Unauthorized(result);
}
Debug.WriteLine(result.ToString()); // this works and I can see the token
return Ok(result);
}
When it comes here:
methods: {
login() {
fetch("http://localhost:60427/api/account/login", {
method: "POST",
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify({
username: this.username,
password: this.password,
})
}).then(response => {
console.log(response.data); // this is always undefined
})
.catch(e => {
console.log(e);
});
},
}
Please help I can't see any errors here. I'm confused.
You need to call either Response.text() or Response.json() depending on what data you expect. These methods return a Promise that resolves to the data.
E.g. for JSON:
fetch("http://localhost:60427/api/account/login", {
method: "POST",
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify({
username: this.username,
password: this.password,
})
})
.then(response => response.json())
.then(data => console.log(data))
.catch(e => console.error(e));

How to make a fetch request to TinyURL?

I am trying to make a fetch request specifically a post request to tinyURL to shortern a url generated on my site. here is the tinyURL API
Currently, I am writing my code like this but it doesn't appear to be returning the short url.
the word tinyurl seems to be banned within links so all links
containing the word tinyurl have been replaced with "SHORT"
here is the tinyURL API https://SHORT.com/app/dev
import * as React from 'react'
interface tinyURlProps { url: string } export const useTinyURL = ({ url }: tinyURlProps) => { React.useEffect(() => {
const apiURL = 'https://api.SHORT.com/create'
const data = JSON.stringify({ url: url, domain: 'tiny.one' })
const options = {
method: 'POST',
body: data,
headers: {
Authorization:
'Bearer xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
Accept: 'application/json',
'Content-Type': 'application/json',
},
} as RequestInit
fetch(apiURL, options)
.then((response) => console.log(response))
.then((error) => console.error(error))
console.log('TinyUrl ran') }, [url])
}
The snippet below seems to work
const qs = selector => document.querySelector(selector);
let body = {
url: `https://stackoverflow.com/questions/66991259/how-to-make-a-fetch-request-to-tinyurl`,
domain: `tiny.one`
}
fetch(`https://api.tinyurl.com/create`, {
method: `POST`,
headers: {
accept: `application/json`,
authorization: `Bearer 2nLQGpsuegHP8l8J0Uq1TsVkCzP3un3T23uQ5YovVf5lvvGOucGmFOYRVj6L`,
'content-type': `application/json`,
},
body: JSON.stringify(body)
})
.then(response => {
if (response.status != 200) throw `There was a problem with the fetch operation. Status Code: ${response.status}`;
return response.json()
})
.then(data => {
qs(`#output>pre`).innerText = JSON.stringify(data, null, 3);
qs(`#link`).href = data.data.tiny_url;
qs(`#link`).innerText = data.data.tiny_url;
})
.catch(error => console.error(error));
body {
font-family: calibri;
}
<p><a id="link" /></p>
<span id="output"><pre/></span>

Cookies not being set immediately in react

I am using djangorestauth for the backend and the token it returns back is not saved in the cookies from universal cookies immediately. I have this handle login:
const handleLogin = (e) => {
e.preventDefault();
setIsClicked(true);
const csrftoken = getCookie("csrf");
const url = "http://localhost:8000/rest-auth/login/";
const cookies = new Cookies();
fetch(url, {
method: "POST",
headers: {
"Content-type": "application/json",
"X-CSRFToken": csrftoken,
},
body: JSON.stringify({
username: username,
password: password,
}),
})
.then((response) => response.json())
.then((key) => setToken(key.key));
cookies.set("token", token);
};
and a useEffect() to test
useEffect(() => {
if (isClicked) {
const cookies = new Cookies();
console.log("THE TOKEN COOKIE: ", cookies.get("token"));
setIsClicked(false);
}
}, [isClicked]);
The problem: When I click the Login button, the token returned was obviously not set immediately because it returns undefined or blank at the first click. And when I input the wrong username and password, the token is still being output
const handleLogin = (e) => {
e.preventDefault();
const csrftoken = getCookie("csrf");
const url = "http://localhost:8000/rest-auth/login/";
const cookies = new Cookies();
fetch(url, {
method: "POST",
headers: {
"Content-type": "application/json",
"X-CSRFToken": csrftoken,
},
body: JSON.stringify({
username: username,
password: password,
}),
})
.then((response) => response.json())
.then((key) => {
setToken(key.key)
cookies.set("token", key.key);
setIsClicked(true);
})
};
explanation
you need to await to finish the fetch
NOTE: setIsClicked change the name to isSubmitSuccess

Server cookies lost on page refresh

I tried fetch to call api and passing credentials "include" to header which set cookies from server initially but on page refresh cookies got lost.
public post = async (payload:any, endpoint: string):Promise<any> => {
return new Promise((resolve, reject) => {
console.log(${config.baseUrl}${endpoint})
const URL = ${config.baseUrl}${endpoint};
fetch(URL, {
credentials: 'include',
method: 'POST',
body: JSON.stringify(payload),
headers: new Headers({
'Content-Type': 'application/json'
})
})
.then(data => data.json())
.then((data:any) => {
console.log("data", data)
const responsePayload = {
statusCode: data.status,
data: data
};
resolve(responsePayload);
})
.catch((error:any) => {
if (error.response === undefined) {
const errorpayload = {
statusCode: 503,
title: 'network error occured',
parameter: 'Network Error',
};
reject(errorpayload);
} else {
const errors = error.response.data.errors;
const errorPayload = {
statusCode: error.response.status,
data: error.response.data.errors,
};
reject(errorPayload);
}
});
});
};
Better read cookies on login and store it to loaclstorage and from there you can use it the way you want.

Call REST API with auth token with React.js

This is a try of call a REST API that as an authentication token with React.js. I'm sending the token request as POST and it's been read as GET, can someone help me please?
componentDidMount() {
fetch("theURL/api-token-auth/", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
email: "EMAIL",
password: "PASSWORD"
}
})
.then(res => {
if (res.ok) {
return res.json();
} else {
throw Error(res.statusText);
}
})
.then(json => {
this.setState({
isLoaded: true,
token: json
});
})
.catch(error => console.error(error));
}
You are correctly using the method POST, so that's not an issue. However, the data you want to send should be in the body instead of in the headers.
componentDidMount() {
const email = "test#example.com";
const password = "foobar";
fetch("theURL/api-token-auth/", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({
email,
password
})
})
.then(res => {
if (res.ok) {
return res.json();
} else {
throw Error(res.statusText);
}
})
.then(json => {
this.setState({
isLoaded: true,
token: json
});
})
.catch(error => console.error(error));
}

Categories

Resources