1

I am working on an angular project; I want to send data to my php mysql but got this error:

"Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://127.0.0.1/angular/post.php. (Reason: missing token ‘content-type’ in CORS header ‘Access-Control-Allow-Headers’ from CORS preflight channel)."

And I have added:

header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");

in my php script.

Here is my php code:

    <?php
        header("Access-Control-Allow-Origin: *");
        header("Content-Type: application/json; charset=UTF-8");

        $conn = mysqli_connect('localhost', 'root', '', 'angular');
        $info = json_decode(file_get_contents('php://input'));
        if(count($info)>0){
            $name = mysqli_real_escape_string($conn, $info->name);
            $age = mysqli_real_escape_string($conn, $info->age);
            $email = mysqli_real_escape_string($conn, $info->email);

            $query = mysqli_query($conn, "INSERT INTO test (`name`, email, age) VALUES ('".$name."', '".$email."', '".$age."')");
            if($query){
                $msg = "Data Added Successfully";
            }
            else{
                $msg = "Data not added Successfully";
            }

            header('Content-Type: application/json');
            echo json_encode($msg);
        }   
    ?>

And my angular dataservice code:

import { Inj

    ectable } from '@angular/core';
    import { HttpClient } from '@angular/common/http';

    @Injectable({
        providedIn: 'root'
    })
    export class DataService {
        theurl: string;

        constructor(private http: HttpClient) {
            this.theurl = 'http://127.0.0.1/angular/';
        }


        sendpost(name, email, age){
            return this.http.post(this.theurl+'post.php', {
                name: name, 
                email: email, 
                age: age
            }).subscribe(
                data => {
                    console.log("post Request is successful ", data);
                },
                error => {
                    console.log("Error", error);
                }
            ); 
        }
    }

And my post.component.ts code:

    import { Component, OnInit } from '@angular/core';
    import { DataService } from '../service/data.service';
    import { Observable } from 'rxjs';

    @Component({
      selector: 'app-posts',
      templateUrl: './posts.component.html',
      styleUrls: ['./posts.component.scss']
    })
    export class PostsComponent implements OnInit {

      constructor(private dataservice: DataService) { }

      ngOnInit() { 
      }
      postam(event){
            event.preventDefault();
            const target = event.target;
            const name = target.querySelector('#name').value
            const email = target.querySelector('#email').value
            const age = target.querySelector('#age').value
            this.dataservice.sendpost(name, email, age)
            // console.log(name, email, age);
        }
    }

And my post.component.html code:

<div class='container'>
    <div class='row'>
        <div class="col-lg-4 col-md-4 col-sm-9">
            <form (submit)="postam($event)">
                <fieldset>
                    <legend>Post data to database</legend>
                    <input type="text" name="name" id="name" class="form-control" placeholder="Enter the name"><br>
                    <input type="email" name="email" id="email" class="form-control" placeholder="Enter the Email"><br>
                    <input type="number" name="age" id="age" class="form-control" placeholder="Enter the Age"><br>
                    <input type="submit" value="Submit" class="btn btn-primary btn-sm pull-right">                  
                </fieldset>
            </form>
        </div>
    </div>
</div>

What seems to be the problem? I have searched the internet for a solution but I didn't find anything that is useful. Please, I need your help.

2
  • 2
    Did you try adding token ‘content-type’ in CORS header ‘Access-Control-Allow-Headers’? It's telling you why the request was being rejected due to the CORS filtering. Commented Sep 4, 2018 at 22:56
  • where will i add it Commented Sep 4, 2018 at 23:00

1 Answer 1

2

Use the following headers in your php file:

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");

Read more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.