首页 > 解决方案 > 无法使用 http.post 离子发送数据

问题描述

我无法使用以下代码通过 http.post 发送数据。我能够得到响应,但无法发送数据进行处理。

以下是代码:

应用服务器.ts

import { Component } from '@angular/core';
import { Http, HttpModule, Headers } from '@angular/http';
import 'rxjs/add/operator/map';

@Component({
  selector: 'server',
  templateUrl: 'home.html'
})
export class appServer {
    connectServer: any;
    send_data: any;
    constructor(private http: Http) {
    }
    serverConnect(){
        let headers = new Headers({'Content-Type': 'application/x-www-form-urlencoded'});
        let req = {call: 'insert_BOT',data: this.send_data};
        this.http.post('http://www.o9village.com/myBOT_api/botfeeds.php',JSON.stringify(req), headers)
        .map(res=>res.json())
        .subscribe(res=>{
            this.connectServer = res;
            console.log(res);
        },(err)=>{
            console.log('Can\'t fetch data');
        })
    }
}

botfeeds.php

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');

echo json_encode($array);

console.log(res) 返回一个空值/

标签: javascriptjavaphptypescriptionic-framework

解决方案


http.post 接受三个参数

1)网址,

2)您要发送的数据,

3)标题

在您指定为 json 但您正在执行 JSON.stringify 的标头中,它会将其转换为字符串,这可能是错误。按原样发送可能会解决问题。

尝试这个

this.http.post('http://www.o9village.com/myBOT_api/botfeeds.php', req, headers)

推荐阅读