React Axios Error in IE 11, but Not Chrome - json

The following works in Chrome, but gives Network Error in IE 11. Same with using Fetch instead of Axios.
What am I missing?
async componentDidMount() {
var auth = "Basic " + btoa(process.env.REACT_APP_CREDENTIAL);
var state = this;
Axios.get(
process.env.REACT_APP_URL,
{
headers: {
Accept: "application/json",
"Content-Type": "application/json",
Authorization: auth,
},
withCredentials: true,
}
)
.then(function (response) {
console.log(response.status);
state.setState({ data: response.data.value });
})
.catch(function (error) {
console.log(error);
});
}

Related

SyntaxError: Unexpected token \n in JSON at position

I have a roblem while directing a request from Cloud Flare workers to my API. When I catch the error I get this:
SyntaxError: Unexpected token \n in JSON at position 240
when I did some research I saw some articles about it being about JSON.parse. But I couldn't find the solution.
Example Request Body:
{"link": "link", "provider": "company", "oauth": "key", "testText": "text"}
Cloud Flare Workers Code:
addEventListener('fetch', function (event) {
const { request } = event;
const response = handleRequest(request).catch(handleError)
event.respondWith(response)
})
async function handleRequest(request) {
const realBody = JSON.parse(`${await request.json()}`
.replace(/\n/g, "\\n")
.replace(/\r/g, "\\r")
.replace(/\t/g, "\\t")
.replace(/\f/g, "\\f"));
const stringifiedJSON = JSON.stringify(realBody);
const init = {
body: stringifiedJSON,
method: "POST",
headers: {
"content-type": "application/json;charset=UTF-8",
},
};
const initLog = {
body: JSON.stringify({ msg: { discountBodyStringified: realBody }}),
method: "POST",
headers: {
"content-type": "application/json;charset=UTF-8",
},
}
const responseLogger = await fetch("https://example.com/log", initLog)
console.log(responseLogger)
console.log(init)
const response = await fetch("https://example.com", init)
return new Response("tweet sent!")
}
function handleError(error) {
console.error('Uncaught error:', error)
const { stack } = error
const initLog = {
body: JSON.stringify({ msg: { error: stack || error }}),
method: "POST",
headers: {
"content-type": "application/json;charset=UTF-8",
},
}
const responseLogger = fetch("https://example.com/log", initLog)
return new Response(stack || error, {
status: 500,
headers: {
'Content-Type': 'text/plain;charset=UTF-8'
}
})
}
problem is not in the code, the problem in request which you are or front app is sending somewhere you lived extra comma or didnt close field.
For example:
{
"name": "Alice",
}
this will give same error as SyntaxError: Unexpected token \n in JSON at position because extra comma is there or
{
"name": "Alice
}
this also will throw error because I didnt close quotes

Get TypeError Network Request Failed using react native fetch json url

I would like to create simple apps that make user can post data to json.
Here is my code.
componentDidMount = () => {
fetch('https://site.json',
{
method: 'POST',
headers: {
"Accept": "application/json",
"Content-Type": 'application/json',
},
body: JSON.stringify({
value: 'React POST Request Example'
})
}
).then(response => response.json()).then(data => console.log(data))
.catch(err => console.log("api Erorr: ", err));
}
But finally, I get an error api Erorr: [TypeError: Network request failed]
Is it Cors block my access???
Any idea how to solve it, Thank you very much
There is something wrong with the URL. The same code working fine with other urls like.
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
value: 'React POST Request Example',
}),
})
.then((response) => response.json())
.then((data) => console.log(data))
.catch((err) => console.log('api Erorr: ', err));
}}

How to convert json to a fetch function in react

the parameter with attribute named file is required and the actual curl command is:- curl -F "file=#password.txt" https://safenote.co/api/file -F password=secret -F lifetime=72 and the corresponding json format is:-
{
"url": "https://safenote.co/api/file",
"raw_url": "https://safenote.co/api/file",
"method": "post",
"files": {
"file": "password.txt"
},
"data": {
"password": "secret",
"lifetime": "72"
}
}
I need this to be converted into a fetch function or using axios, I'm not understanding which is the body part ad what to include
I have tried :-
fetch(`https://safenote.co/api/file`,{
mode:'no-cors',
method:"POST",
// headers: {
// "Content-Type": "application/json"
// },
"files":{
"file":selectedFile,
},
// body: JSON.stringify({
// file:selectedFile
})
// })
.then(response => response.json())
.then(data => console.log("data",data))
.catch(error => console.log(error));
}
my HTML part
<input type="file" name="attachment" accept="image/png, image/jpeg" onChange={(e) => setSelectedFile(e.target.files[0])}/>```
You can use axios and form data for that
const myFormData = new FormData();
myFormData.append('files', 'file');
You can add another properties like name or whatever too
myFormData.append('name', 'myFileName');
then use the axios
axios({
method: "post",
url: "myurl",
data: myFormData,
headers: { "Content-Type": "multipart/form-data" },
})
.then(function (response) {
//handle success
console.log(response);
})
.catch(function (response) {
//handle error
console.log(response);
});

Fetching from API in React with key in headers, returning 406 not acceptable

I'm trying to fetch from an API, using an API key, but keep getting 406 Not Acceptable.
I can get the request to work in Postman, but not in the code. What could be wrong here? I've tried all sorts of ways of including my info in headers, this is just my last attempt.
componentDidMount() {
fetch("my-api", {
method: "GET",
headers: ({
Accept: "application/json",
"Content-Type": "application/json",
"X-Api-Version": 20161108,
Authorization: {
Token: "my-api-key",
}
}),
body: JSON.stringify()
}).then(response => {
if (response.status === 201) {
console.log(response)
return response.json()
} else {
console.log("oh no!", response.status === 404)
}
})
}
I figured it out. This ended up working:
componentDidMount() {
fetch("my api", {
method: "GET",
headers: ({
Accept: "application/vnd.api+json",
"Content-Type": "application/json",
"X-Api-Version": 20161108,
Authorization: "Token my token",
}),
body: JSON.stringify()
}).then(response => {
if (response.status === 200) {
console.log(response)
return response.json()
} else {
console.log("oh no!", response.status === 404)
}
})
}

How can i get response from fetch API React Native

{
"success":true,
"result":{
"sessionName":"2a7777703f6f219d"
"userId":"19x1"
"version":"0.22"
}
};
fetch('https://myapi/api', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
firstParam: 'xxxx1',
secondParam: 'xxxx1',
})
})
How can i get response from fetch API React Native (Post method)
I need to console.log to see sessionName in result (I think it's response.result.sessionName)
But I don't know how to get it from fetch.
Where is response from fetch like a get method
Here's Get method from facebook (it's have response)
function getMoviesFromApiAsync() {
return fetch('https://facebook.github.io/react-native/movies.json')
.then((response) => response.json())
.then((responseJson) => {
return responseJson.movies;
})
.catch((error) => {
console.error(error);
});
}
You can just do the same as GET method:
fetch('https://myapi/api', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
firstParam: 'xxxx1',
secondParam: 'xxxx1',
})
})
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);// your JSON response is here
})
.catch((error) => {
console.log(error);
});