0
I need to check if a user already exists before registering.
I have the following methods:
Register.component.ts:
import { AlertService } from './../alert.service';
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { UserService } from '../user.service';
@Component({
selector: 'app-register',
templateUrl: './register.component.html',
styleUrls: ['./register.component.css']
})
export class RegisterComponent{
model: any = {};
loading = false;
constructor(private router: Router,
private userService: UserService,
private alertService: AlertService) { }
register(){
this.loading = true;
this.userService.create(this.model)
.subscribe(
data => {
console.log(data);
this.alertService.success('Registro realizado com sucesso!', true);
},
error => {
this.alertService.error(error);
this.loading = false;
});
}
}
My method in the user service:
create(user: Usuario) {
return this.http.post('http://localhost/api/api.php', JSON.stringify(user));
}
My api:
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
$servername = "localhost";
$username = "root";
$password = "";
// Create connection
$conn = new mysqli($servername, $username, $password,'mydb');
$user = json_decode(file_get_contents('php://input'),true);
if(isset($user['username'])){
$sql = "INSERT INTO users (first_name, last_name, username,password)
VALUES ('".$user['firstName']."', '".$user['lastName']."', '".$user['username']."','".$user['password']."')";
mysqli_query($conn, $sql);
echo json_encode(array('response'=>'sucess'));die;
}
mysqli_close($conn);
?>
I put in the bd the username as Unique thinking it would return some error, but still missing something in my implementation. How and where I should check if the username already exists?
I made the changes but now returns to my console: "Blocked cross-origin request: Same Origin Policy (Same Origin Policy) prevents reading the remote resource at http://localhost/api/api.php. (Reason: CORS header 'Access-Control-Allow-Origin' is not present)." I already have in my header: header("Access-Control-Allow-Origin: *"); header("Content-Type: application/json; charset=UTF-8");
– veroneseComS
That I do not understand, but there is something here in Marcelo’s answer in this post https://cursos.alura.com.br/forum/topico-requisicao-cross-origin-blocked
– user60252
You can also search here at this page by
Requisição cross-origin bloqueada
that you must find some solution to your case– user60252