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
})
)
};
Related
I am trying to create a web app that uploads file and attached the current user to the file model as a foreign key. For some reason the get request is being wiped, but it does initially get the needed information.
handleSubmit = (e) => {
e.preventDefault();
axios.get('http://127.0.0.1:8000/core/current_user/', {
headers: {
Authorization: `JWT ${localStorage.getItem('token')}`,
}
}).then((user) => {
this.state.creator = user.data;
console.log(this.state.creator);
})
console.log(this.state.creator);
let form_data = new FormData();
form_data.append('creator', this.state.creator);
form_data.append('file', this.state.file);
form_data.append('title', this.state.title);
form_data.append('description', this.state.description);
axios.post('http://localhost:8000/core/posts/', form_data, {
headers: {
'Content-Type': 'multipart/form-data',
Authorization: `JWT ${localStorage.getItem('token')}`,
}
}).then(res => {
console.log(res.data);
}).catch(err => console.log(err))
};
The 1st console is returning the user information but the 2nd console returns null. Any help will be really appreciated.
Your then statement after the original get ends on line 11, and the rest of your code is outside of that.
With asynchronous code, the code outside of the then block will continue running while it's waiting for a response, so this.state.creator will not have been set yet. Then it will return to the code inside the then block once the promise resolves.
You need to move all of the second block of code inside the intial then block so it is only executed once a response to the original get request has returned:
handleSubmit = (e) => {
e.preventDefault();
axios
.get('http://127.0.0.1:8000/core/current_user/', {
headers: {
Authorization: `JWT ${localStorage.getItem('token')}`,
},
})
.then((user) => {
this.state.creator = user.data;
console.log(this.state.creator);
let form_data = new FormData();
form_data.append('creator', this.state.creator);
form_data.append('file', this.state.file);
form_data.append('title', this.state.title);
form_data.append('description', this.state.description);
axios
.post('http://localhost:8000/core/posts/', form_data, {
headers: {
'Content-Type': 'multipart/form-data',
Authorization: `JWT ${localStorage.getItem('token')}`,
},
})
.then((res) => {
console.log(res.data);
})
.catch((err) => console.log(err));
});
};
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.
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);
});
I want to communicate with the server.
In order to communicate with the server, two items must be added to headers.
Note: The key value written is not the actual key value.
api_key: "abcdegeg123456842536ebebeb1yeyju",
game_key: "abcdegeg123456842536ebebeb1yeyju"
The code I tried to communicate with:
checkNickName = async () => {
fetch("http://192.168.0.44:11000/v1/point/auth/change_nickname", {
method: "POST",
body: JSON.stringify({
wallet_address: "0f8751828af26816ef996c37e611b945304a6e99",
new_nickname: this.state.nickname
}),
headers: {
// "Content-Type": "application/json"
api_key: "abcdegeg123456842536ebebeb1yeyju",
game_key: "abcdegeg123456842536ebebeb1yeyju"
}
})
.then(res => res.json())
.then(response => {
console.log("response:" + response);
console.log(response.resultCode);
if (response.resultCode == "S000") {
Alert.alert("info","scess");
} else alert(response.result);
})
//console.log("Success:", JSON.stringify(response))
.catch(error => console.error("Error:", error));
};
But this is not working
Error:, [TypeError: Network request failed]
How can I communicate with the server? Is there another way?
thank you in advance
It was a mistake in my address,
but the server receiving the data says the data is null. How can we solve the problem?
I solved it by using formdata.
usePage.js
async checkNickName() {
let formdata = new FormData();
formdata.append(
"wallet_address",
"gBx0f8751828af26816ef996c37e611b945304a6e99"
);
formdata.append("new_nickname", this.state.nickname);
fetch("http://192.168.0.26:11000/v1/point/auth/change_nickname", {
method: "POST",
body: formdata,
headers: {
"Content-Type": "multipart/form-data",
api_key: "5b95576338b1eb1c53a1ae3f904dc7c5",
game_key: "bf61b73dd871c2973188706d813002c2"
}
})
.then(res => res.json())
.then(response => {
console.log(response);
console.log(response.resultCode);
if (response.resultCode == "S002") {
AsyncStorage.setItem("gbrickobj", this.state.gbrickobj);
AsyncStorage.setItem("nickname", this.state.nickname);
this.props.navigation.navigate("RegisterSecurity");
} else if (response.resultCode == "S001") {
this.setState({
checknick: "this nickname already use nickname."
});
} else {
Alert.alert("info", "check address.");
}
})
.catch(error => console.error("Error:", error));
}
The following code is a React action that is supposed to dispatch to a reducer. I can't seem to get the return statement to run. I can get it to hit a debugger right blelow the data variable declaration, but that's it. If I try to run the rest of the code within debugger, I'm getting a reference error "Return is not a function". I can't figure out what I'm missing here. Any help would be greatly appreciated. Thanks in advance.
const baseUrl = 'http://localhost:3001'
export const signUp = (user) => {
let data = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({ user })
}
return dispatch => {
fetch(`${ baseUrl }/signup`, data)
.then(response => response.json())
.then(user => {
sessionStorage.setItem('user', user)
dispatch({
type: 'SET_USER',
payload: user.current
})
})
.catch(err => err)
}
}
Well if you are using redux-thunk you are missing the parameters inside for your function and currently you have just user. Try this:
export const signUp = (dispatch, getState, user) => {
...your code
}