Please help...
I'm new in this forum.
I've an apllication that I will send to php api data to save into mysql.
My code Ionic 5
let headers : any = new HttpHeaders({ 'Content-Type': 'application/json' });
let item: {
"nome" : "Sueli",
"email" : "[email protected]",
"senha" : "123456",
"nivel" : "admin"
}
var link = 'http://localhost/project2MJA/usuarios/criarUsuario.php';
var myData = JSON.stringify(item);
this.http.post(link, myData, headers)
.subscribe(data => {
console.log(data["_body"]);
}, error => {
console.log(data['message']);
});
My code php
<?php
// headers
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-
Requested-With");
// obtém conexão
include_once '../config/database.php';
// instancia objeto usuário
include_once '../objects/usuario.php';
$database = new Database();
$db = $database->getConnection();
$usuario = new Usuario($db);
// recebe dados via POST - Body
$data = json_decode(file_get_contents("php://input"));
// certifica que os dados estão preenchidos
if(
!empty($data->nome) &&
!empty($data->email) &&
!empty($data->senha) &&
!empty($data->nivel)
){
// define as propriedades
$usuario->nome = $data->nome;
$usuario->email = $data->email;
$usuario->senha = $data->senha;
$usuario->nivel = $data->nivel;
// cria o usuário
if($usuario->criarUsuario()){
// define código de resposta - 201 created
http_response_code(201);
// mensagem para o usuário
echo json_encode(array("message" => "Usuário criado com sucesso."));
}else{ // caso não cadastre o usuário exibe mensagem
// define código de resposta - 503 service unavailable
http_response_code(503);
// mensagem de usuário não cadastrado
echo json_encode(array("message" => "Usuário não pode ser criado."));
}
}else{ // mensagem de dados incompletos
// define codigo de resposta - 400 bad request
http_response_code(400);
// mensagem para usuário
echo json_encode(array("message" => "Usuário não criado. Dados incompletos."));
}
I run ionic serve and test to save data and i receive the message:
POST http://localhost/project2MJA/usuarios/criarUsuario.php 400 (Bad Request)
[error from ionic][1]
You are not assigning the value to item, you are declaring the type. In other words you are using : instead of =, it should be,
let item = {
"nome" : "Sueli",
"email" : "[email protected]",
"senha" : "123456",
"nivel" : "admin"
}
That might be the problem.
BTW, I don't think you need the header and to stringify the data of the post. If I recall well (it's been several years since I do anything in PHP), you can get the values using $_POST in the backend (in your case as an example $_POST['nome']).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With