Angular 6 httpclient发布在console.log中给出错误

时间:2018-09-04 22:54:30

标签: angular angular6 angular-httpclient

我正在做一个有角度的项目;我想将数据发送到我的php mysql,但收到此错误:

"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)."

我添加了:

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

在我的php脚本中。

这是我的php代码:

    <?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);
        }   
    ?>

我的角度数据服务代码:

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);
                }
            ); 
        }
    }

还有我的post.component.ts代码:

    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);
        }
    }

还有我的post.component.html代码:

<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>

似乎是什么问题?我已经在互联网上搜索了解决方案,但没有找到任何有用的方法。拜托,我需要你的帮助。

1 个答案:

答案 0 :(得分:2)

在您的php文件中使用以下标头:

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

了解更多:https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS