Angular 4 Typescript http post请求无效

时间:2017-06-04 14:56:52

标签: php angular typescript http-post

我正在尝试通过对服务器上的php文件发出http post请求来为我的类项目创建一个工作联系表单。我知道php文件有效,因为当我直接路由它时它会ping我的电子邮件,当我在浏览器中调试时,我可以看到它正在尝试构建http请求。我遇到的问题是我真的不明白我在做什么......我希望有人可以告诉我我的代码有什么问题,或者指出我正确的方向。任何帮助将不胜感激......这是我到目前为止所拥有的:

headers = {
    'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
}

data = {
    name:'name',
    phone:'555-5555',
    email:'email@gmail.com',
    message:'hello'
}

constructor(private http: Http) { }

postData() {
    console.log(this.data);
    this.http.post('http://mywebsite.net/contact_me.php', 
this.data, this.headers);
}

2 个答案:

答案 0 :(得分:1)

我也面临这个问题

  

step1在php文件中设置标题

header("Access-Control-Allow-Origin: *");

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

您可以获得回复的示例函数

   public function createAction(Request $request) {

    $data=file_get_contents('php://input');

    var_dump($data);//here you print you 'POST' or 'GET' Response.
  

step2 service.ts formService.ts

 private headers = new Headers({'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'});

 private insertdataUrl = 'api-url';

 //create function that is called by component.html file
  create(user: ApiDashboard) {
   return this.http.post(this.insertdataUrl,user).map(response => response.json());

   }
  //here in my code ApiDashboard is model 
  

step3在component.ts文件中定义服务功能

export class ApiDashboardformComponent implements OnInit {
model: any = {};
 loading = false;
  constructor(private router: Router,
    private formService: FormService
    ) { }

 ngOnInit() {
 }
Create() {
    this.loading = true;
        this.formService.create(this.model)
        .subscribe(
            data => {
                this.formService.success('Registration successful', true);
                this.router.navigate(['/material-dashboard']);
            },
            error => {
                this.formService.error(error);
                this.loading = false;
            });
      }
     }
  

step4最后调用create()函数component.html文件

 <div class="col-md-6 col-md-offset-3">
  <h2>Register</h2>
  <form name="form" (ngSubmit)="f.form.valid && Create()" #f="ngForm" novalidate>

答案 1 :(得分:0)

将此添加到我的php文件中:

header("Access-Control-Allow-Origin: http://localhost:4200");

并将我的body参数更新为:

JSON.stringify(this.data)

我仍然遇到问题,我的标题param以“未定义”的形式返回,但这足以至少用空消息ping我的电子邮件。谢谢您的帮助!