从Angular材质textarea向服务器发送Http POST XML数据

时间:2019-07-13 12:59:25

标签: angular angular-material http-post

我设置了一个接受XML输入的服务器。 我想从有角度的前端发送XML消息。我对angular非常陌生!

我使用棱角材质创建了一个文本区域,在其中写入了xml input。 这是我要发送的XML:

<SendMessage>
    <Message Name="Test1" Message="Test2" Version="01.00"/>
</SendMessage>

我更新了 MessageService 以添加标题,并且我手动编写了一些示例xml只是为了查看它是否适用于以下代码:

@Injectable()
export class MessageService {

  private url: string;

  constructor(private httpClient: HttpClient) {
    this.url = 'http://localhost:8080/bg/sendMessage';
  }

  createMessage() {
    const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type': 'application/xml',
        'Accept': 'application/xml',
        'Response-Type': 'text'
      })
    };
    const postedData = `
      <SendMessage>
         <Message Name="Test1" Message="Test2" Version="01.00"/>
      </SendMessage>`;
    return this.httpClient.post(this.url, postedData, httpOptions).subscribe(
      result => {
        console.log('The result is:', result);
      },
      error => console.log('There was an error', error)
    );
  }
}

然后我也更新了 MessageComponent

export class MessagesComponent {

  constructor(public messageService: MessageService) {
  }

  onFormSubmit() {
    this.messageService.createMessage();
  }
}

这是我的 Message.html 文件,我刚刚在其中添加了按钮的click事件。当我单击按钮时,我应该能够发送xml:

    <mat-card>
  <form  >
    <mat-card-content>
      <mat-form-field >
        <textarea  matInput placeholder="Xml Message"></textarea>
      </mat-form-field>
    </mat-card-content>
    <mat-card-actions>
      <button  mat-raised-button (click)="onFormSubmit()">Send Message</button>
    </mat-card-actions>
  </form>
</mat-card>

不幸的是,我收到错误消息“发生了错误” ,并且

POST http://localhost:8080/bg/sendMessage net::ERR_FAILED

当我在浏览器中检查网络时,没有响应,并且sendMessage失败。

然后我检查了后端,发现它在前端发送请求时抛出了错误。

后端中的错误是:不支持内容类型'text / plain'

对于 Content-Type 我使用的是 application / xml ,我不知道问题可能在哪里!

关于我可以改善以至少得到回应的任何建议?

P.S。我用Postman测试了后端,一切正常。

0 个答案:

没有答案