User registration with React, Axios and PHP backend - javascript

I need to register a new user with API. Back-end developer gave me screenshot how he implemented registration on PhP. Unfortunately, he doesn't know react so he can't help me. I already have input forms saving them in state. Could you please help me what's going on in the picture below and how make registration on React.
and my code. Let me know if I missing any field. I have url , but I dont know where to add user/create, company/create links:
signUp(event) {
event.preventDefault()
const formdata = new FormData()
formdata.append("email", this.state.userLogin.email)
formdata.append("password", this.state.userLogin.password)
formdata.append("name", this.state.userLogin.name)
formdata.append("companyName", this.state.userLogin.companyName)
formdata.append("region", this.state.userLogin.region)
axios
.post("http://dev.***********.com/", formdata)
.then(res => {
if (res.data) {
console.log('success')
this.props.history.push("/settings")
}
})
.catch(error => {
console.log(error)
})
}

you are missing some fields for the post request,
but this is how I would do it:
const data = {
username: YOU_NEED_THIS,
label: YOU_NEED_THIS,
label_short: YOU_NEED_THIS,
email: this.state.userLogin.email,
password: this.state.userLogin.password,
name: this.state.userLogin.name,
companyName: this.state.userLogin.companyName,
region: this.state.userLogin.region,
};
axios
.post("http://dev.***********.com/", data)
.then(.....)

Related

how to get user input values and post them with axios

I've built a contact form and I'm trying to get my user inputted values to post using axios so I then get an email with the data inputted by the user.
I keep getting undefined values in my emails being sent. My server side is fine, I'm not to worried about that. What's the best approach for this?
document.querySelector(".contact-btn").addEventListener("click", sendIt);
function sendIt(event) {
event.preventDefault();
axios
.post("https://us-central1-selexin-website.cloudfunctions.net/app/sendemail", {
name: "",
email: "",
number: "",
message: "",
})
.then((res) => {
console.log(res);
});
}
this might work, also you can re-read documentation on POST Request Axios Documentation
For Live view how it works you can check on CODEPEN
const form = document.querySelector("form")
const input = document.querySelector("input")
const submitUser = () => {
axios.post('https://us-central1-selexin-website.cloudfunctions.net/app/sendemail', {
firstName: input.value,
})
.then(response => {
console.log(response);
})
.catch(error => {
console.log(error);
});
}
form.addEventListener("submit", (e) => {
submitUser()
e.preventDefault()
})
<form>
<input type="text">
<button type="submit">Submit</button>
</form>

Axios POST Request only logged after page is refreshed and not functioning

recently I tried to familiarize myself with React Native.
I found that the POST request for my login method only logged in after the page is refreshed. The POST message also seems like it has been stalled. Unfortunately, this error only occurs on my PC environment, not on my friend's PC.
I'm not sure what is the factor that causes this issues. Would love if anyone had any idea why this only appear on certain PC environment.
Login.js
handleLoginFormSubmit = e => {
e.preventDefault();
const { username, password } = this.state;
axios
.post("/users/login", {
username: username,
password: password
})
.then(res => {
this.setState({
message: "success",
isLoggedIn: true,
});
})
.catch(err => {
this.setState({
username: "",
password: "",
message: `${err.response.data}`
});
});
}
You need async await, because fetching data need uncertain time
Add async on this line
handleLoginFormSubmit = async (e} =>
And await on this line
await axios

JS await throws an error in a browser console

I'm using nuxt to develop a client for my laravel project.
In the login.vue component I have the following JS code
import Form from 'vform'
export default {
head () {
return { title: this.$t('login') }
},
data: () => ({
form: new Form({
email: '',
password: ''
}),
remember: false
}),
methods: {
async login () {
let data;
// Submit the form.
try {
const response = await this.form.post('/api/login');
data = response.data;
} catch (e) {
return;
}
// Save the token.
this.$store.dispatch('auth/saveToken', {
token: data.token,
remember: this.remember
});
// Fetch the user.
await this.$store.dispatch('auth/fetchUser');
// Redirect home.
this.$router.push({ name: 'home' })
}
}
}
If I try to submit the login form with wrong email and password values I see an error message in a browser console.
For example:
POST http://laravel.local/api/login 422 (Unprocessable Entity)
Please note that I'm using try catch that catches all errors on the following call.
const response = await this.form.post('/api/login');
Is this really issue with async/await usage?
How can I get rid of that error in the browser console?
If you need some more info from me do not hesitate to ask it.

How to use one update function for all fields of a specific model in REST API?

I am using Django REST Framework and React for a project. I have a API route called /api/account/user/ which accepts both GET and POST requests (RetrieveUpdateAPIView). Now, in my React front end, I have this function in my actions file that I would like to use to update user data:
export const updateUser = (email, name, company, phoneVerified, idVerified) => {
return (dispatch, getState) => {
const token = getState().auth.token
let headers = {
'Content-Type': 'application/json'
}
if (token) {
headers['Authorization'] = `Token ${token}`
}
let body = JSON.stringify({email, name, company, phoneVerified, idVerified})
return fetch('//localhost:8000/api/account/user/', {headers, body, method: 'POST'})
.then(res => {
if (res.status < 500) {
return res.json().then(data => {
return {status: res.status, data}
})
}
else {
console.log('Server error.')
}
})
.then(res => {
console.log(res)
if (res.status === 200) {
dispatch({type: 'USER_UPDATE_SUCCESSFUL', data: res.data})
return res.data
}
else if (res.status === 403 || res.status === 401) {
dispatch({type: 'USER_UPDATE_FAILED', data: res.data})
return res.data
}
else {
dispatch({type: 'USER_UPDATE_FAILED', data: res.data})
return res.data
}
})
}
}
This function works if I pass all parameters (email, name, company, phoneVerified, idVerified), but for example, if I want to only update phoneVerified on a button click event, how do I pass only that parameter? Currently I am doing this:
updateUser: (phoneVerified) => dispatch(auth.updateUser(phoneVerified))
But the server response is This field may not be null. Any help with this will be very much appreciated.
It is not the problem of React, it is how you handle in backend code.
You use HTTP POST method in rest API, by default it uses to create one record
You should implement other HTTP method handling for your endpoint, it is PUT method, but with PUT, you still need to send whole object with updated property to update it (Generally, PUT should use to update the record entirely)
Another HTTP method fit your case much better, it is PATCH method, just like PUT but you can just send the updated property to server with the record id (PATCH should use to update the record partially).
For both case, just SHOULD, not MUST because it is the standard convention of HTTP, it is not restricted. Even you still can use GET method to create record.
It depends on your backend code as well. But the line JSON.stringify({name, ...}) will render {name: null, ...} if name is null. So you're sending null values for all the attributes you're not updating. I would change that code to exclude those attributes altogether.

How do I pass a react DOM state's information to backend(NodeJS) when a button is invoked?

I'm using his logic on the frontend, but I'm having some trouble actually receiving that data on the backend. I'm using the Sails.js framework. Any suggestions?
handleSubmit = () => {
// Gathering together the data you want to send to API
const payload = {
subject: this.state.subject,
message: this.state.message,
};
this.handleAjaxRequest(payload);
};
// Method to send data to the backend
// Making the req -I'm using Axios here.
handleAjaxRequest = (payload) => {
let request = axios({
method: 'post',
url: '/api/',
data: payload,
headers: 'Content-Type: application/json'
});
// Do stuff with the response from your backend.
request.then(response => {
console.debug(response.data);
})
.catch(error => {
console.error(error);
})
};
I used to do this using Express and didn't have these problems.
Any help, method, a suggestion is more than welcome :)
Please forgive my ignorance, I'm just here to learn.
Okay, so the first thing I had to do is generate a new restful API using the command sails generate api data. In the package.json file I set up a proxy that includes the backends endpoint, like this "proxy": "http://localhost:1337" - I mean, you don't need to do this, but if you don't then you have to include this URL part on every request. Because it doesn't change, it's pretty convenient to do so.
On the frontend, I made a function sendData() that takes the necessary data from my previous component (depending on what the user selected) and send that data using axios to the backend -->
sendData = () => {
const { relYear } = this.props.history.location.state.dev;
const { relMonth } = this.props.history.location.state.dev;
const selectedMonth = moment().month(relMonth).format("MM");
const finalSelect = parseInt(relYear + selectedMonth, 10);
axios.post('/data', { 'selectedDate' : finalSelect })
.then(res => console.log('Data send'))
.catch(err => console.error(err));
}
On the backend I fetched the data, did the calculations and send back the result to the frontend of my app. -->
getApiData = () => {
let apiData = [];
axios.get('/data')
.then(res => {
let first = Object.values(res.data.pop()).shift(); // Getting the relevant 'selectedDate'
apiData.push(first);
}).catch(err => console.error(err));
return apiData;
}

Categories