Fetch not giving me the response - javascript

I have a login form with username and password field. I am trying to send the username and password to my django api. But nothing shows up in console. I am trying to print response in console. THis is my code
export default class LogInComponent extends Component {
handleLoginButtonClick() {
fetch('https://myname-backend.appspot.com',{
method: "POST",
type: 'json',
data: {password:document.getElementById("username").value,
username:document.getElementById("password").value
}
})
.then(function(response) {
// We get a JWT back.
let jwt = response.auth_token;
// We trigger the LoginAction with that JWT.
console(response);
//LoginActions.loginUser(jwt);
return response;
});
}
render() {
return (
<div className="LoginPage">
<div className="login-page">
<div className="form">
<form className="register-form">
<input type="text" placeholder="name"/>
<input type="password" placeholder="password"/>
<input type="text" placeholder="email address"/>
<button>create</button>
<p className="message">Already registered? Sign In</p>
</form>
<form className="login-form">
<input id="username" type="username" placeholder="username"/>
<input id="password" type="password" placeholder="password"/>
<button onClick={this.handleLoginButtonClick}>login</button>
<p className="message">Not registered? Request Username and Password</p>
</form>
</div>
</div>
<img className="Logo_Tessact_White" src="./dev/js/images/TESSACT_logo_white.png"/>
</div>
);
}
}
This my api call guide
What am I doing wrong?
Updated Code
export default class LogInComponent extends Component {
handleLoginButtonClick() {
fetch('https://myname-backend.appspot.com/auth/login', {
method: "POST",
type: 'json',
data: {
"password": document.getElementById("password").value,
"username": document.getElementById("username").value
}
}
)
.then(function(response) {
return response.json();
})
.then(function(data) {
// We get a JWT back.
let jwt = data.auth_token;
// We trigger the LoginAction with that JWT.
console.log(data);
//LoginActions.loginUser(jwt);
return data;
});
//browserHistory.push("app")
// console.log('clicked')
// console.log(document.getElementById("password").value);
}
render(){
return (
<div className="LoginPage">
<div className="login-page">
<div className="form">
<form className="register-form">
<input type="text" placeholder="name"/>
<input type="password" placeholder="password"/>
<input type="text" placeholder="email address"/>
<button>create</button>
<p className="message">Already registered? Sign In</p>
</form>
<form className="login-form">
<input id="username" type="username" placeholder="username"/>
<input id="password" type="password" placeholder="password"/>
<button onClick={this.handleLoginButtonClick}>login</button>
<p className="message">Not registered? Request Username and Password</p>
</form>
</div>
</div>
<img className="Logo_Tessact_White" src="./dev/js/images/TE_logo_white.png"/>
</div>
);
}
Still not able to get the console printing the response.

The url seems to be wrong. You have:
fetch('https://myname-backend.appspot.com',{
and should have:
fetch('https://myname-backend.appspot.com/login',{

You are passing incorrect data i.e username in password and password in username.
Use
data: {password:document.getElementById("password").value,
username:document.getElementById("username").value
}

Related

ReactJs | get the userID back from the API according to the login input

I have a login component where the user can log in with email and password. In the database, the user have following properties.
1.userID
2.Email
3.Password
I want to get the userid back from the API according to the user login. Cansome genius help me with this?
my login component:
export default class Login extends Component {
state = {};
submitHandler = e => {
e.preventDefault()
const logingdata ={
email : this .Email,
password: this .Password
}
axios
.post('/api/UserLogin', logingdata)
.then(response => {
console.log(response); //to print response in console in developper tool
//const currentuser = JSON.parse(atob(response.data.token.split(".")[1]));
localStorage.setItem('login', response.data.token);
console.log(this.email);
})
.catch(error => {
console.log(error => console.log(error.response.data))
})
}
render() {
return (
<div className="outer">
<div className="inner">
<form onSubmit={ this.submitHandler}>
<h3>Log in</h3>
<div className="form-group">
<label>Email</label>
<input type="text" className="form-control" placeholder="Enter email" onChange ={ e => this.Email = e.target.value} />
</div>
<div className="form-group">
<label>Password</label>
<input type="text" className="form-control" placeholder="Enter password" onChange ={ e => this.Password = e.target.value} />
</div>
<div className="form-group">
<div className="custom-control custom-checkbox">
<input type="checkbox" className="custom-control-input" id="customCheck1" />
<label className="custom-control-label" htmlFor="customCheck1">Remember me</label>
</div>
</div>
<br></br>
<button type="submit" className="btn btn-dark btn-lg btn-block">Sign in</button>
<p className="forgot-password text-right">
Forgot <Link to= "/Forgotpassword" >password?</Link>
</p>
</form>
</div>
</div>
);
}
}
EDIT:
console response hen login: (it shows only username and password)

i created registration form on reactjs, my registration form seems working but i didn't get any email verification

just like the title said i created registration form using react js, at first it's working when finish fill the form it link to another page. But the problem is after user fill all the form it suppose to automatically send email verification and i didn't get any email verification. can anyone help me with this problem, i still new using react jS. any help would be appreciated...
this is my code if anyone wondering:
import React, { Component } from 'react';
import {Redirect, Link, router } from 'react-router-dom';
import './SignUp.css';
import axios from 'axios';
export default class Login extends Component {
componentDidMount() {
window.scrollTo(0, 0)
}
constructor(props) {
super(props);
this.state={
company: '',
province: '',
city: '',
website: '',
address: '',
contact:'',
password:'',
email:'',
errors: {}
}
this.handleChangeCompany = this.handleChangeCompany.bind(this);
this.handleChangeWebsite = this.handleChangeWebsite.bind(this);
this.handleChangeProvince = this.handleChangeProvince.bind(this);
this.handleChangeCity= this.handleChangeCity.bind(this);
this.handleChangeAddress = this.handleChangeAddress.bind(this);
this.handleChangeMobile = this.handleChangeMobile.bind(this);
this.handleChangeEmail = this.handleChangeEmail.bind(this);
this.handleChangePassword = this.handleChangePassword.bind(this);
this.submituserRegistrationForm = this.submituserRegistrationForm.bind(this);
}
handleChangeWebsite(e) {
this.setState({website:e.target.value});
}
handleChangeProvince(e) {
this.setState({province:e.target.value});
}
handleChangeCity(e) {
this.setState({city:e.target.value});
}
handleChangeCompany(e) {
this.setState({company:e.target.value});
}
handleChangeAddress(e) {
this.setState({address:e.target.value});
}
handleChangeEmail(e) {
this.setState({email:e.target.value});
}
handleChangeMobile(e) {
this.setState({contact:e.target.value});
}
handleChangePassword(e) {
this.setState({password:e.target.value});
}
submituserRegistrationForm(e) {
e.preventDefault();
if (this.validateForm()) {
var apiBaseUrl = "http://THIS_IS_MY_API_:3000";
var data={
"query":"mutation{ createProfile( profileInput :{company: \""+this.state.company+"\", address: \""+this.state.address+"\", email: \""+this.state.email+"\", contact: \""+this.state.contact+"\", province: \""+this.state.province+"\", city: \""+this.state.city+"\", website: \"\", operational: 24, password: \""+this.state.password+"\"}){ _id company address city province email contact website logo createdAt updatedAt } }"
}
/*console.log(data);*/
var headers = {
'Content-Type': 'application/json',
}
axios.post(apiBaseUrl, data, {headers: headers}).then(function (response) {
if(response.data.data){
console.log(response.data.data);
localStorage.setItem("u_code", encodeURIComponent(JSON.stringify(response.data.data)));
localStorage.setItem('is_done', true);
window.location.href = "/login";
console.log("Sign Up successfull");
}else{
alert(response.data.message);
}
}).catch(function (error) {
console.log(error);
});
}
}
validateForm() {
let errors = {};
let formIsValid = true;
return formIsValid;
}
render() {
return (
<div className="container-fluid">
<div className="row no-gutter">
<div className="d-none d-md-flex col-md-4 col-lg-6 bg-image" />
<div className="col-md-8 col-lg-6">
<div className="login d-flex align-items-center py-5">
<div className="container">
<div className="row">
<div className="col-md-9 col-lg-8 mx-auto">
<h3 className="login-heading mb-4">Sign Up Now!</h3>
<form method="post" name="userRegistrationForm" onSubmit= {this.submituserRegistrationForm}>
<br></br>
<h5 className="login-heading mb-4"><u>Company</u></h5>
<div className="form-label-group">
<input name="company" value={this.state.company} onChange={this.handleChangeCompany} id="company" className="form-control" placeholder="Company" required autofocus />
<label htmlFor="company">Company</label>
</div>
<br></br>
<h5 className="login-heading mb-4"><u>City</u></h5>
<div className="form-label-group">
<input name="City" value={this.state.city} onChange={this.handleChangeCity} className="form-control" placeholder="City" required autofocus />
<label>City</label>
</div>
<br></br>
<h5 className="login-heading mb-4"><u>Address</u></h5>
<div className="form-label-group">
<input name="address" value={this.state.address} onChange={this.handleChangeAddress} className="form-control" placeholder="Address" required autofocus />
<label>Address</label>
</div>
<br></br>
<h5 className="login-heading mb-4"><u>Province</u></h5>
<div className="form-label-group">
<input name="Province" value={this.state.province} onChange={this.handleChangeProvince} className="form-control" placeholder="Province" required autofocus />
<label >Province</label>
</div>
<br></br>
<h5 className="login-heading mb-4"><u>Email Address</u></h5>
<div className="form-label-group">
<input name="email" value={this.state.email} onChange={this.handleChangeEmail} className="form-control" placeholder="Email" required autofocus />
<label>Email</label>
</div>
<br></br>
<h5 className="login-heading mb-4"><u>Contact</u></h5>
<div className="form-label-group">
<input name="contact" value={this.state.contact} onChange={this.handleChangeMobile} className="form-control" placeholder="Contact Number" required autofocus />
<label>Contact</label>
</div>
<br></br>
<h5 className="login-heading mb-4"><u>Password</u></h5>
<div className="form-label-group">
<input type="password" value={this.state.password} onChange={this.handleChangePassword} name="password" id="inputPassword" className="form-control" placeholder="Password" required />
<label htmlFor="inputPassword">Password</label>
</div>
<br></br>
<button value="Login" className="btn btn-lg btn-primary btn-block btn-login text-uppercase font-weight-bold mb-2" type="submit">Sign Up</button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
);
}
}
it's seems nothing wrong with the code it just i put Json web token in the wrong place.
the correct one is like this :
const getJWT = () => {
return localStorage.getItem('token');
};
const jwt = getJWT();
if (!jwt){
window.location.href = "/";
};
instead of this, it created another token and thats why the server did not recognize because of unrecognized token :
localStorage.setItem("u_code", encodeURIComponent(JSON.stringify(response.data.data)));
localStorage.setItem('is_done', true);
in the header i just put jwt like this :
'Authorization' : 'Tesla '+jwt+''

Show bootstrap alert with condition (Vue.js): how can I access this variable in order to change its value?

First of all I would like to apologize if the answer to my question is obvious, however since I'm still pretty new to Vue.js, I'm getting really stuck here and I need help.
I got an authentication system and if the user wants to register without putting in an username, I would like to show an bootstrap alert. The code looks like this right now:
<template>
<div class="container">
<div class="row">
<div class="col-md-6 mt-5 mx-auto">
<form v-on:submit.prevent="register">
<h1 class="h3 mb-3 font-weight-normal">Register</h1>
<div class="form-group">
<label for="username">Username</label>
<input
type="text"
v-model="username"
class="form-control"
name="username"
placeholder="Please choose your username"
>
</div>
<div class="form-group">
<label for="email">Email Address</label>
<input
type="email"
v-model="email"
class="form-control"
name="email"
placeholder="Please enter your email address"
>
</div>
<div class="form-group">
<label for="password">Password</label>
<input
type="password"
v-model="password"
class="form-control"
name="password"
placeholder="Please choose your password"
>
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit">Register</button>
</form>
<div>
<b-alert variant="success" show>Example alert</b-alert>
</div>
<div>
<b-alert variant="danger" :show="showAlert">Example Alert!</b-alert>
</div>
</div>
</div>
</div>
</template>
<script>
import axios from "axios";
import router from "../router";
export default {
data() {
return {
username: "",
email: "",
password: "",
showAlert: false };
},
methods: {
register() {
axios
.post("/user/register", {
username: this.username,
email: this.email,
password: this.password
})
.then(res => {
if (!res.data.username) {
// show an alert, I would like to do something similar to "showAlert = true;"
} else {
// redirect to login
}
})
.catch(err => {
console.log(err);
});
}
}
};
</script>
<style scoped>
#import "../assets/css/reglog.css";
#import "../assets/css/modal.css";
</style>
However I'm not sure how to access the showAlert variable neither how to change its value in the if-statement. The only thing that I know here is that if I change the showAlert manually in the code (line 9 counting from the script tag) from false to true, the page does react and shows the alert when wanted.
I'm sorry if you need more information or if something is unclear, I'm a bit tired and stuck with this for some hours, not gonna lie.
You can access showAlert variable following: this.showAlert = true
.then(res => {
if (!res.data.username) {
this.showAlert = true; // update showAlert
} else {
// redirect to login
}
})

Post json data using fetch api failed

Am new in javascript , and am trying to POST data with an API endpoint but data is not posting , I have printed in the console , but I see Slow network is detected. See https://www.chromestatus.com/feature/5636954674692096 for more details. Fallback font will be used while loading: https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/fonts/fontawesome-webfont.woff2?v=4.7.0 in Google chrome.
But internet connection is good and stable.
This is my vanilla javascript for posting data :
function onSignUp() {
signupform
var email = document.signupform.email_edt.value;
var driver_rb = document.getElementById("driver_rb").checked;
var password_edt = document.signupform.password_edt.value;
var r_password_edt = document.signupform.r_password_edt.value;
var url = 'https://tuvuge-app.herokuapp.com/api/v1/signup';
//var data = {username: 'example'};
var data = {
username: email,
email: email,
password: password_edt,
isDriver: 'True'
};
fetch(url, {
method: 'POST',
body: JSON.stringify(data), // data can be `string` or {object}!
headers: {
'Content-Type': 'application/json'
}
}).then(res => res.json())
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', response));
}
Then I attached the onSignUp() function to the button in html as below :
<form class="admin-modal-content" name="signupform" onSubmit="onSignUp();" action="index.html" method="post">
<div class="container">
<h4>Sign Up</h4>
<p>Please fill in this form to create an account.</p>
<hr>
<label for="email">
<b>Email</b>
</label>
<input type="email" placeholder="you#example.com" id="email_edt" name="email_edt" required>
<label for="email">
<b>Select an Option</b>
</label>
<p>
<input type="radio" name="driver_rb" value="driver" id="driver_rb">
<label>Driver</label>
</p>
<p>
<input type="radio" name="passenger_rb" id="passenger_rb" value="passenger">
<label>Passenger</label>
</p>
<label for="psw">
<b>Password</b>
</label>
<input type="password" placeholder="Enter Password" id="password_edt" name="password_edt" required>
<label for="psw-repeat">
<b>Repeat Password</b>
</label>
<input type="password" placeholder="Repeat Password" id="r_password_edt" name="psw-r_password_edt" required>
<div class="clearfix">
<button type="submit" class="btn">Sign Up</button>
</div>
</form>
What am I missing ,because the endpoint has a message it brings when there's a success or failure of data posting , but I see the above message.
What am I missing?

How to use $asyncValidators with angularjs and set a warning message in the HTML

This is my first bigger form with validations and etc.
I've created a Registration form and I'm using ng-messages for validation. The problem is that I need to validate the username, does it already exist in the JSON server that we are using or it's available. Of course, if it's taken the warning pops out in the HTML where the username input is, if it's available the submit button is no more disabled (because the form will be $valid) and the user can register. I want to use angular-sanitize because I found this (I don't know if they are related):
ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) {
var value = modelValue || viewValue;
// Lookup user by username
return $http.get('/api/users/' + value).
then(function resolved() {
//username exists, this means validation fails
return $q.reject('exists');
}, function rejected() {
//username does not exist, therefore this validation passes
return true;
});
};
Here is the code I use now (reg form, controller and service):
// Controller:
export default class registerPageController {
constructor(userService, authenticationService, $location) {
this.register = "Register";
this.userService = userService;
this.$location = $location;
this.authenticationService = authenticationService;
this.hasLoggedIn = false;
}
onSubmit(user) {
let self = this;
let {
name,
age,
email,
username,
password
} = user;
self.userService.register(name, age, email, username, password).then((res) => {
self.userService.login(username, password).then(function (response) {
let data = response.data;
if (data.length) {
let user = data[0];
self.hasLoggedIn = true;
self.authenticationService.setCredentials(username, password);
self.$location.path('/');
}
});
})
.catch(err => {
// WHAT TO PUT HERE AFTER THE USERNAME EXIST VALIDATION ?
})
}
}
// Service:
export class UserService {
constructor($http) {
this.$http = $http;
}
login(username, password) {
return this.$http({
method: 'GET',
url: 'http://localhost:3000/users',
params: {
username: username,
password: password
}
});
}
register(name, age, email, username, password) {
return this.$http({
method: 'POST',
url: 'http://localhost:3000/users',
data: {
name: name,
age: age,
email: email,
username: username,
password: password
}
});
}
// SHOULD I PUT HERE THE USERNAME EXIST VALIDATION LOGIC ?
}
<div class="container main-content">
<form class="registrationForm" name="registerForm" ng-submit="register.onSubmit(register.user)" novalidate="novalidate">
<!-- Enter Name -->
<div class="form-group">
<label for="name" class="control-label"><span id="reqInfo">*</span> Name</label>
<input type="text" name="name" class="form-control" ng-model="register.user.name" ng-pattern="/[a-zA-Zа-яА-Я]+/" id="name"
required="" placeholder="Example: Petar Petrov">
<div ng-messages="registerForm.name.$error" ng-show="registerForm.name.$touched" style="color:maroon" role="alert">
<div ng-message="required">Your name is required</div>
</div>
</div>
<!-- User Age-->
<div class="form-group">
<label for="age" class="control-label"><span id="reqInfo">*</span> Age</label>
<input type="number" name="age" class="form-control" ng-model="register.user.age" ng-min="18" min="18" id="age" required=""
placeholder="Enter your age">
<div ng-messages="registerForm.age.$error" ng-show="registerForm.age.$touched" style="color:maroon" role="alert">
<div ng-message="min">You must be at leats 18 years old</div>
</div>
</div>
<!-- Enter E-mail -->
<div class="form-group">
<label for="email" class="control-label"><span id="reqInfo">*</span> E-mail</label>
<input type="email" name="email" class="form-control" ng-model="register.user.email" ng-pattern="/((([A-Za-z]{3,9}:(?:\/\/)?)(?:[\-;:&=\+\$,\w]+#)?[A-Za-z0-9\.\-]+|(?:www\.|[\-;:&=\+\$,\w]+#)[A-Za-z0-9\.\-]+)((?:\/[\+~%\/\.\w\-_]*)?\??(?:[\-\+=&;%#\.\w_]*)#?(?:[\.\!\/\\\w]*))?)/"
id="email" required="" placeholder="Example: mail#mail.net">
<div ng-messages="registerForm.email.$error" ng-show="registerForm.email.$touched" style="color:maroon" role="alert">
<div ng-message="required">Your valid e-mail is required</div>
</div>
<br>
<!-- Enter Username -->
<div class="form-group">
<label for="username" class="control-label"><span id="reqInfo">*</span> Username</label>
<input type="text" name="username" ng-minlength="5" ng-maxlength="20" class="form-control" ng-model="register.user.username"
ng-pattern="/^[A-Za-z0-9_]{1,32}$/" ng-minlength="7" id="username" required="" placeholder="Enter your username">
<div ng-messages="registerForm.username.$error" style="color:maroon" role="alert">
<div ng-message="minlength">Your Username must be between 7 and 20 characters long</div>
</div>
<br>
<!-- Enter Password -->
<div class="form-group">
<label for="password" class="control-label"><span id="reqInfo">*</span> Password</label>
<input type="password" name="password" class="form-control" ng-model="register.user.password" ng-minlength="7" id="password"
required="" placeholder="Enter your password">
<div ng-messages="registerForm.password.$error" style="color:maroon" role="alert">
<div ng-message="minlength">You Password must be at least 7 symbols long</div>
</div>
</div>
<!-- Register button -->
<div class="form-group">
<button class="btn btn-primary" type="submit" ng-disabled="!registerForm.name.$valid || !registerForm.age.$valid || !registerForm.email.$valid || !registerForm.username.$valid || !registerForm.password.$valid">Register</button>
</div>
<p>Fields with <span id="reqInfo">*</span> must be filled.</p>
</form>
</div>
Important is to know that I have being told explicitly to write it in ES6.
I have problem with the logic so look at my code and please fill it for me so I can use it and most important - learn it :S
Thank you so so much in advance!
I have implemented a directive for different kind of validations (sync Async), and it supports warning as well.
You may check it from
`https://plnkr.co/2WQHOo`
If this is what you needed and need more information, let me know I will try my best to answer.

Categories