这是我的代码。我向posts-experiencias.php文件发出http发布请求,并且试图通过$ _REQUEST全局变量获取数据,但我什么也收不到。你知道为什么吗?
post.service.ts
import { Injectable } from '@angular/core';
import { HttpHeaders, HttpClient } from '@angular/common/http';
import { Post } from './post';
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
})
};
@Injectable({
providedIn: 'root'
})
export class PostService {
private postsUrl = 'http://local.blog.com/controllers/posts-experiencias.php';
getPostsSegunSeccion(seccion) {
const obj = {
nome: 'gabriel',
age: 20
};
return this.http.post(this.postsUrl, JSON.stringify(obj), httpOptions);
}
}
post.component.ts
import { Component, OnInit } from '@angular/core';
import { PostService } from './post.service';
import { Post } from './post';
@Component({
selector: 'app-posts',
templateUrl: './post.component.html',
styleUrls: ['./post.component.css']
})
export class PostComponent implements OnInit {
seccion: string;
constructor(private postService: PostService) {}
actualizarPosts(event) {
this.seccion = event.target.attributes['data-categoryvalue'].value;
this.postService.getPostsSegunSeccion(this.seccion)
.subscribe((data) => {
console.log(data)
});
}
}
答案 0 :(得分:1)
这样做:
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
})
};
您已将Content-Type
设置为application/json
。这意味着您的服务器将期望JSON有效负载。
但是通过在JSON.stringify(obj)
中执行getPostsSegunSeccion
,实际上是在发送string
而不是JSON
对象。
因此,您需要从JSON.stringify
中删除getPostsSegunSeccion
,这应该可以为您解决问题。您的getPostsSegunSeccion
应该类似于:
getPostsSegunSeccion(seccion) {
const obj = {
nome: 'gabriel',
age: 20
};
return this.http.post(this.postsUrl, obj, httpOptions);
}
答案 1 :(得分:0)
在我的情况下,由于它以Json格式接收数据,因此我不得不使用file_get_contents('php:// input'),而不是使用$ _REQUEST来接收它们。
posts-experiencias.php
// Collect the data that has been sent in Json format (String)
$dataInJsonString = file_get_contents('php://input');
// decode Json
$decodedData = json_decode($dataInJsonString);
echo $decodedData->age;
echo $decodedData->nome;