Angular HTTPClient POST主体未发送

时间:2018-06-30 21:25:38

标签: javascript node.js angular post angular-httpclient

当前,我正在尝试将名称,电子邮件和消息从一个有角度的前端发布到在同一nginx服务器中运行的php脚本,然后该服务器运行phpmailer来发送包含名称,电子邮件和消息的电子邮件。这是到目前为止的代码:

import { Component, OnInit } from '@angular/core';
import { Email } from './email';
import {ContactService} from './contact.service';
import {HttpClient, HttpHeaders} from '@angular/common/http';
import {NgForm} from '@angular/forms';

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type':  'application/x-www-form-urlencoded'
  })
};

const email = new Email('', '', '');

@Component({
  selector: 'app-contact',
  templateUrl: './contact.component.html',
  styleUrls: ['./contact.component.css'],
  providers: [ContactService]
})
export class ContactComponent implements OnInit {

  email = new Email('', '', '');

  constructor(private http: HttpClient) { }

  sendEmail(form: NgForm) {
    const value = form.value;
    const senderName = value.name;
    const senderEmail = value.email;
    const senderMessage = value.message;
    this.sendMail(senderName, senderEmail, senderMessage);
  }

  sendMail(senderName, senderEmail, senderMessage) {
    console.log(senderName + ' ' + senderEmail + ' ' + senderMessage);
    this.http.post('https://ruffstuffcostumes.tk/assets/scripts/email.php',
      {
        name: senderName,
        email: senderEmail,
        message: senderMessage,
      },
      httpOptions
      )
      .subscribe(
        (val) => {
          console.log('POST call successful value returned in body',
            val);
        },
        response => {
          console.log('POST call in error', response);
        },
        () => {
          console.log('The POST observable is now completed.');
        });
  }

  ngOnInit() {
  }

}

当我通过邮递员运行POST请求以检查它时,它运行得很好,并发送了包含所需元素的电子邮件,但是,尽管我使用此脚本执行了查询,即使console.log(senderName + ' ' + senderEmail + ' ' + senderMessage)确实显示了值,似乎根本没有将它们发布在正文中,而我得到的全部事实是,即使已发送邮件,但在邮件正文中发送时都没有这些值。

这可能是跨源问题(如果是的话,解决该问题的最佳方法是什么?),或者我只是在犯一些愚蠢的错误?

1 个答案:

答案 0 :(得分:1)

仅出于完整性考虑。我通过切换到发送JSON数据并在php端进行解析来解决了问题