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);
});
Related
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));
}}
If I do this in PostMan, I get a response back which I can toggle html and json, but in my react native app I'm getting a console error of JSON Parse Error: Unexpected EOF
I have the content type of my sent header as x-www-form-urlencoded because that was the only way to get my proper response even on postman.
I have my backend in wordpress sending a response array as json_encoded (echo json_encode($response)) and I can get it by url and post man, but my app just can't get past this unexpected EOF and I think it has to do with my .then statements
WHat am I doing wrong here?
validate(){
const {navigate} = this.props.navigation;
this.setState({ validating: true });
let formData = new FormData();
formData.append('type', 'login');
formData.append('email', this.state.email);
formData.append('password', this.state.password);
return fetch('https:/site/authentication.php', {
method: 'POST',
body: JSON.stringify(formData),
headers:{
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.then(response => response.json())
.then(data => {
console.log(data);
return data;
})
.catch(function(err) {
console.log(err);
})
}
Looking at your response:
Response { "_bodyBlob": Blob { "_data": Object { "blobId": "31418cda-5d2e-4ee0-8c67-626e7ebe0502", "offset": 0, "size": 0, }, }, "headers": Headers { "map": Object { "cache-control": "public, max-age=0", "content-length": "0", "content-type": "text/html; charset=UTF-8", }, }, "ok": true, "status": 200, "statusText": undefined, "type": "default", "url": "https://site/authentication.php", } Promise { "_40": 0, "_55": null, "_65": 0, "_72": null, }
I think it is a blob not JSON. Try and use this instead:
.then(response => response.blob())
Sorry I missed that earlier.
Blob MDN Ref: response.blob()
I'm working with a JSON rest API that has the following response:
// response
[
{
id: 1,
userId: 1,
start: "2018-01-01 10:15",
finish: "2018-01-01 12:20",
breakLength: 30
},
{
id: 2,
userId: 1,
start: "2018-01-02 10:15",
finish: "2018-01-02 18:20",
breakLength: 45
}
];
See below for code. Like my other functions, I am requesting a GET using fetch(). However, sometimes this function when called requests and responds with a 200, and sometimes it responds with a 400 bad request(Uncaught (in promise) SyntaxError: Unexpected token B in JSON at position 0) It seems very random when it happens. My server which the JSON Rest API is on is localhost:3000 and my application is on localhost:3001. I have used this same method for other JSON requests and they work perfectly. I am not sure why this one is having trouble? Thanks for your help!
Update: It seems as though the last Promise.all, setState is not being executed. The program is crashing on line .then(response => response.json()) in promise3.
Updated Code:
getShifts = (sessionId) => {
return fetch("http://localhost:3000/shifts", {
method: "GET",
headers: {
"Accept": "application/json",
"Content-Type": "application/json",
"Authorization": sessionId
}
});
};
callbackSessionId = (sessionId) => {
let promise1 = this.fetchUserAttributes(sessionId)
.then(response => response.json())
.then(json => this.setState({
userAttributes: json
}));
Promise.all([promise1]).then(() => {
let promise2 = this.getOrganisations(sessionId)
.then(response => response.json())
.then(json => this.setState({
organisations: json
}));
let promise3 = this.getShifts(sessionId)
.then(response => response.json())
.then(json => this.setState({
shifts: json
}));
// this.setState({
// sessionId: sessionId
// });
Promise.all([promise2, promise3]).then(() => {
this.setState({
sessionId: sessionId
});
});
});
};
Your JSON is actually invalid. All keys need to be string literals, so your correct JSON would look like this:
[
{
"id": 1,
"userId": 1,
"start": "2018-01-01 10:15",
"finish": "2018-01-01 12:20",
"breakLength": 30
},
{
"id": 2,
"userId": 1,
"start": "2018-01-02 10:15",
"finish": "2018-01-02 18:20",
"breakLength": 45
}
]
There are a few issues in your code: you should always return your promises, headers property names should be quoted and React setState is an asynchronous method.
Please, try to update it like below to see if it works, I'll edit expanding on the details if it does.
getShifts = (sessionId) => {
return fetch("http://localhost:3000/shifts", {
method: "GET",
headers: {
"Accept": "application/json",
"Content-Type": "application/json",
"Authorization": sessionId
}
});
};
fetchData = (sessionId) => {
let promise3 = this.getShifts(this.state.sessionId)
.then(response => response.json())
.then(json => this.setState({shifts: json}, this.forceUpdate));
};
I'm getting a serialized JSON body from our API like the below example: '
{
"_embedded": [
{
"id": 1,
"vulnerable": false,
"systemId": "something",
"friendlyName": "a friendly name"
},
]
}
How to show just the key/value friendlyName? I'm using axios to get the response. This is my code:
axios.get(BASE_URL + 'household/list',{
headers: { Authorization: AuthStr },
transformResponse: axios.defaults.transformResponse.concat((data) => {
console.log(data) // this should now be JSON
})
}).then(({ data })=> {
this.setState({
data: houses.friendlyName
});
})
.catch((err)=> {
console.log(err);
});
I think I'm supposed to transform the data, but I don't know how. Thanks for any help.
Edit: This is how the response is shown in console:
_embedded:
0:
friendlyName: "a friendly name"
id: 1
systemId: "GE8BP2IACH7"
vulnerable: false
So, how do I deserialize it?
axios.get(BASE_URL + 'household/list',{
headers: { Authorization: AuthStr },
}).then(function (response) {
this.setState({data:response._embedded.friendlyName})
})
.catch(function (error) {
console.log(error);
});
{
"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);
});