Display server response in vuejs template - arrays

I am using vuejs and backend Django. When i send request to server then it send response i had use console to display any error in console log. The problem is that i want that response to display in vuejs template. so i don`t have any idea.. so what can i do??
login: function () {
// for storing token sent by server
axiosInstance({
method: 'post',
url: '/auth/jwt/create/',
data: {
'password': this.credentials.password,
'email': this.credentials.email
}
})
.then(response => {
this.non_field_errors.push(response.data.non_field_errors)
console.log(response)
console.log(response.data.token)
this.$cookie.set('accesstoken', response.data.token, 1)
this.$cookie.set('usertype', response.data.usertype, 1)
console.log(this.$cookie.get('usertype'))
this.$router.push('/')
})
.catch(e => {
this.errors.push(e)
console.error(e)
})
}
}

First, declare a property in data object.
data: function() {
errors: null
}
You can set the value of it like this.
login: function () {
let that = this
// for storing token sent by server
axiosInstance({
method: 'post',
url: '/auth/jwt/create/',
data: {
'password': this.credentials.password,
'email': this.credentials.email
}
})
.then(response => {
//if success
})
.catch(e => {
//if catch an error
// set e or any of its props
that.errors = e
})
}
To display:
<pre v-text="errors"></pre>
Updated
working fiddle: https://fiddle.jshell.net/Zugor/601tdxoe/

Related

Fetch().then() does not return data

I am having some trouble in getting fetch return data from my cloud function, I am only trying to write data into google spreadsheet with cloud function for now. Below is my current code so far.
I have a button with onClick={this.AddRecord} which will then call the cloud function
AddRecord = async () => {
await fetch(url, {
method: 'POST',
body: JSON.stringify({
date: this.getDate(),
name: this.state.name,
number: '\'' + this.state.number
})
})
.then((response) => {return response.json()})
.then((data) => {
alert(data) // this never gets executed
this.setState({message:data})
})
.catch((err) => {
this.setState({message: err})
});
}
and this is my cloud function POST handler:
case 'POST':
/* parse the string body into a usable JS object */
const data = JSON.parse(event.body);
const addedRow = await sheet.addRow(data);
return {
statusCode : 200,
body: JSON.stringify({
message : 'Posted successfully.',
rowNumber: addedRow._rowNumber - 1 // minus the header row
})
};
Appreciate it if anyone could point me in the right direction, as I have spent a lot of time trying to debug this but with no avail.
some of the resource that I have read so far:
fetch() call not returning any data
https://www.smashingmagazine.com/2020/06/rest-api-react-fetch-axios/
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
Edit:
I have tried to call the cloud function via POSTMAN and successfully gotten a status 200 response with message.
So I can safely assume that the issue is not with the cloud function but the fetch function, but I am still clueless on which part of the code went wrong as they seem pretty much the same as other code example that I see online. I will only get TypeError: Failed to fetch when I switch back to POST from my react app.
Change your function to this:
AddRecord = async () => {
await fetch(url, {
method: 'POST',
headers: { 'Content-Type':'application/json' }, // here is the change
body: JSON.stringify({
date: this.getDate(),
name: this.state.name,
number: '\'' + this.state.number
})
})
.then((response) => response.json())
.then((data) => {
alert(data)
this.setState({message:data})
})
.catch((err) => {
this.setState({message: err})
});
}

In React while submitting a sign in, am getting my password and email in (Localhost)URL as query string?

After running my project in Localhost and and giving my information's for signin , am getting this in my URL
http://localhost:3000/?email-address=roopa%40gmail.com&password=roopa3
and i also checked for "onClick" in my events, but everything is ok..
event.preventDefault();
console.log('emailchanged')
this.setState({signinEmail: event.target.value})
}
onPasswordchange = (event) => {
event.preventDefault();
console.log('passwordchanged')
this.setState({signinPassword: event.target.value})
}
onSubmitSignin = () => {
console.log('entered onsubmitsignin..') // after this console msg again my localhost redirects me to a new signin page which giving inputs to URL as query strings
fetch('http://localhost:8050/signinpage/', {
method: 'post',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
email: this.state.signinEmail,
password: this.state.signinPassword
})
})
.then(function (response) {
console.log(response.status);
return response.json();
})
.then(res => {
if(res.ok){
this.props.onRoutechange('Home');
}
else if (!res.ok) {
throw new Error("HTTP status " + res.status);
}
})
}
I don't need my inputs to show as query string here..!

axios post data as form data instead of as JSON in payload

I am just trying my first reactJS app.
In that I am using axios.post() method for sending data.
submitHandler = event => {
event.preventDefault();
axios
.post("http://demo.com/api/v1/end-user/login", {
username: "",
password: "",
user_type: 1
})
.then(res => {
console.log(res);
console.log(res.data);
});
}
But when I check into my network tab, data which I am sending along with request is seems to be in payload.
I would like to send the data as form data instead. Am I am missing something?
If you want to send the data as form data instead of as JSON in the payload, you can create a FormData object and use that as second argument instead.
submitHandler = event => {
event.preventDefault();
const formData = new FormData();
formData.append("username", "");
formData.append("password", "");
formData.append("user_type", 1);
axios.post("http://demo.com/api/v1/end-user/login", formData).then(res => {
console.log(res);
console.log(res.data);
});
};
You can do this in axios by using FormData() like
var body = new FormData();
body.append('userName', 'test');
body.append('password', 'test');
body.append('user_type', 1);
And then you can use axios post method (You can amend it accordingly)
axios({
method: 'post',
url: 'http://demo.com/api/v1/end-user/login',
data: body,
config: { headers: {'Content-Type': 'multipart/form-data' }}
})
.then(function (response) {
//handle success
console.log(response);
})
.catch(function (response) {
//handle error
console.log(response);
});
What worked for me is to send the form trough params: instead of data:
That way it will be send as GET variables instead of Request Payload and is much easier to read with $_GET in PHP. No idea how to send as post
axios({
method: 'post',
params: data,
url: 'api.php',
})
.then((res) => {
//Perform Success Action
})
.catch((error) => {
// error.response.status Check status code
}).finally(() => {
//Perform action in always
});

Why can't I define an object first and then send that object as a body in post requests? (React)

I'm trying to do a simple POST request using React's fetch() method, but when I try to add my data object to the body of that request it gets undefined when it arrives in my express-based back-end (and yes, i'm already using body-parser etc.).
However, if I instead define the body directly in the fetch() method by manually adding the properties, it suddenly works the way I want it to.
This is on the client-side:
addProduct = (event) => {
event.preventDefault();
const data = {
namn: this.state.curNamn,
lagersaldo: this.state.curSaldo,
plats: this.state.curPlats
}
if (this.checkEmptyValues(data)) {
alert("Please fill in all the fields");
return;
}
fetch('http://localhost:3001/addproduct', {
method: 'POST',
headers: {'Content-Type':'application/json'},
body: JSON.stringify({data})
})
.then(res => this.resolveRes(res))
.catch((err) => console.log(err))
}
And on the server-side:
app.post('/addproduct', (req, res) => {
let data = {
namn: req.body.namn,
lagersaldo: req.body.lagersaldo,
plats: req.body.plats
};
let sql = 'INSERT INTO produkter SET ?';
db.query(sql, data, (err, result) => {
if (err) throw err;
res.send(result);
});
});
So the above code gives me a 'ER_BAD_NULL_ERROR' since the properties of the body are undefined when it arrives on the server-side, but If i were to change the code to this it works:
addProduct = (event) => {
event.preventDefault();
if (this.checkEmptyValues(data)) {
alert("Please fill in all the fields");
return;
}
fetch('http://localhost:3001/addproduct', {
method: 'POST',
headers: {'Content-Type':'application/json'},
body: JSON.stringify({
namn: this.state.curNamn,
lagersaldo: this.state.curSaldo,
plats: this.state.curPlats
})
})
.then(res => this.resolveRes(res))
.catch((err) => console.log(err))
}
Why is this? Why can't i just define and create the object that i want to send first, and then just send that object in the body?
You are wrapping your data inside a another object
JSON.stringify({data})
// This gets stringified to:
{
data: {
namn: ...,
lagersaldo: ...,
plats: ...
}
}
Replace with:
JSON.stringify(data)
//Stringifies to:
{
namn: ...,
lagersaldo: ...,
plats: ...
}
Your are sending data in another object here:
fetch('http://localhost:3001/addproduct', {
method: 'POST',
headers: {'Content-Type':'application/json'},
body: JSON.stringify({data})
})
You should spread data if you have to add something
fetch('http://localhost:3001/addproduct', {
method: 'POST',
headers: {'Content-Type':'application/json'},
body: JSON.stringify({
...data,
newFixValue: true
})
})
or just send data like this:
fetch('http://localhost:3001/addproduct', {
method: 'POST',
headers: {'Content-Type':'application/json'},
body: JSON.stringify(data)
})

Fetch request always returns network error

I almost finished creating React Native application, few days ago register action has stopped working.. I'm sending fetch request and it always returns network error altough there is 400 response and message that user exists, it stops there..
I'm destructuring the response and displays api response message instead of fetch network error but now it doesn't work. I'm doing the same for the login action and it works.
Could it be something with multipart/form-data ?
export const register = data => dispatch => {
dispatch(createUser());
const d = new FormData();
d.append("name", data.name);
d.append("email", data.email);
d.append("password", data.password);
d.append("avatar", data.avatar);
fetch(API_URL + "/register", {
method: "POST",
headers: {
"content-type": "multipart/form-data"
},
body:d
})
.then(response => response.json().then(user => ({ user, response })))
.then(({ user, response }) => {
if (!response.ok) {
console.log(response, user)
} else {
console.log(response, user)
}
})
.catch(err => {
throw err;
});
};
The api route works in Postman..
In this case, your using fetch which is Promise based incorrectly,
Try,
fetch(API_URL + "/register", {
method: "POST",
headers: { "content-type": "multipart/form-data" },
body:d
})
.then(response => {
console.log(response, response.json().user)
})
.catch(err => {
console.log(err)
});
Check the logs and see if it shows proper network response and debug from there.

Resources