You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular4 CLI设置application/json头时Http.post后端无法获取POST数据

解决Angular POST JSON到CodeIgniter后端无法获取数据的问题

嗨,我来帮你搞定这个问题!你遇到的情况很常见——CodeIgniter默认不会自动解析application/json类型的POST请求,它只处理application/x-www-form-urlencoded和multipart/form-data这两种格式的数据,所以当你用JSON格式发送时,后端用$this->input->post()就拿不到数据啦。下面给你两种解决方案,选一种适合你的就行:

方案一:修改CodeIgniter后端,支持JSON解析

在你的admin_api控制器的index方法里,先判断请求头类型,如果是JSON就读取原始输入流并解码,这样就能拿到数据了:

public function index() {
    // 检查请求是否为JSON格式
    if ($this->input->server('CONTENT_TYPE') === 'application/json') {
        // 读取原始POST数据
        $raw_post_data = file_get_contents('php://input');
        // 解码为关联数组
        $post_data = json_decode($raw_post_data, true);
        
        // 现在就可以像普通POST数据一样使用了,比如:
        // $username = $post_data['username'];
        // $password = $post_data['password'];
    } else {
        // 兼容原有x-www-form-urlencoded格式的请求
        $post_data = $this->input->post();
    }

    // 后续的业务逻辑处理...
}

方案二:修改Angular前端,发送x-www-form-urlencoded格式数据

如果你不想改动后端,那就调整前端代码,把JSON对象转成表单编码格式的字符串发送:

首先在你的DataService里添加一个辅助函数,用来把对象转成urlencoded格式:

@Injectable()
export class DataService {
  constructor(private http:Http) { }

  // 新增:把对象转成x-www-form-urlencoded字符串
  private toFormEncoded(data: any): string {
    return Object.keys(data)
      .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(data[key])}`)
      .join('&');
  }

  getWhere(url, resource){
    let headers= new Headers();
    headers.append('Accept','text/plain');
    // 换回application/x-www-form-urlencoded类型
    headers.append('content-type','application/x-www-form-urlencoded');
    let option= new RequestOptions({headers:headers});
    // 用辅助函数转换数据,替代JSON.stringify
    return this.http.post(url, this.toFormEncoded(resource), option)
      .map(response=>response.json())
      .catch(this.handleError);
  }

  // ...其他代码
}

另外还要注意你的AuthService里的signIn方法,你现在传入的是HTMLInputElement,这可能不对哦,应该传入包含用户名密码的对象,比如:

signIn(credentials: { username: string; password: string }){
    this.dataService.getWhere(this.url, credentials)
      .subscribe(response=>{
        console.log(response);
      });
}

这样调整后,后端就能用$this->input->post('username')这类方法正常获取数据了~

内容的提问来源于stack exchange,提问作者Mandip Vora

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 06:41:18