This question already has answers here:
Receive JSON POST with PHP
(12 answers)
Closed 8 months ago.
I am trying to experiment with Redux Toolkit Query mutations.
What I have now at the front-end:
import { createApi, fetchBaseQuery } from "#reduxjs/toolkit/query/react";
export const postApi = createApi({
reducerPath: "postApi",
baseQuery: fetchBaseQuery({
baseUrl: "https://webcodingcenter.com/shared/",
prepareHeaders: (headers, { getState }) => {
headers.set("Content-Type", "application/json");
return headers;
}
}),
endpoints: (builder) => ({
getPost: builder.query({
query: (id) => `get_post.php?id=${id}` // expects a JSON response
}),
updatePost: builder.mutation({ // <-- attention here
query: (body) => {
console.log(123, body);
return {
url: `update_post.php`,
method: "POST",
body
};
}
})
})
});
// Export hooks for usage in functional components, which are
// auto-generated based on the defined endpoints
export const { useGetPostQuery, useUpdatePostMutation } = postApi;
And the back end (update_post.php):
<?php
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Methods: HEAD, GET, POST, PUT, PATCH, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method,Access-Control-Request-Headers, Authorization");
header('Content-Type: application/json');
if ($_SERVER['REQUEST_METHOD'] == "OPTIONS") {
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method,Access-Control-Request-Headers, Authorization");
header("HTTP/1.1 200 OK");
die();
}
$str="HELLO WORLD";
$r="";
for ($i = 0; $i < strlen($str); $i++){
if (rand(0,100)>50) $r .= strtoupper($str[$i]);
else $r .= strtolower($str[$i]);
}
file_put_contents("data".$_POST["id"].".txt",$r);
echo json_encode($_POST);
//echo json_encode(array("post"=>$r));
?>
As you can see from the Code Sandbox here, $_POST is always empty. How can I pass the data to $_POST?
This solves it:
$data = json_decode(file_get_contents('php://input'), true);
Related
I have problem with request POST in fetch function. I make REST API with react and PHP and I get error Access-Control-Allow-Origin is required. I have this header in my web api. This is my code (begin) in PHP:
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET,POST,PUT,DELETE");
header("Access-Control-Expose-Headers: access-control-allow-origin");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
header("Content-Type: application/json; charset=UTF-8");
and in React:
//method = POST
//body = {"name":"test","body":"test"}
const apiCall = (url, method, body, resolve, reject) => {
fetch(url, {
method: method,
headers: {
'Content-Type': 'application/json; charset=utf-8'
},
body: JSON.stringify(body)
}).then(resp => {
if(resp.ok) {
resp.json().then(json => resolve(json));
}
else {
reject(resp);
}
});
}
I try to communicate with other server and api - result was the same.
Screen with error in Google Chrome browser:
screen
Please help.
You have to add the CORS MODULE and Proxy in Server.
I'm sure this is an easy one, hopefully it's easy. In setting up axios (with VUE) and trying to post something, anything, POST is not received. Postman works fine, my vue app with Axios however does not, the POST array arrives empty.
The outgoing request payload in devtools has the variables (at the moment just 'test'='test.
From Vue
this.$axios.post("http://localhost/api/process.php?action=addEntry", {
test:"test"
}).then(function (response) {
alert(JSON.stringify(response));
})
.catch(function (error) {
alert("error");
alert(JSON.stringify(error));
});
return
},
From PHP Api - process.php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: User-Agent, Sec-Fetch-Mode, Referer, X-Requested-With, Content-Type, Origin, Cache-Control, Pragma, Authorization, Accept, Accept-Encoding");
header("Access-Control-Allow-Methods: POST");
header('Content-Type: application/json;charset=UTF-8');
echo (var_dump($_POST['test']));
echo (var_dump($_POST));
Output
The POST is not available.
The response
The headers
Try this
axios.post("urlapi",
data: {
foo: 'bar', // This is the body part
}, {
headers: {
'Content-Type': 'application/json'
}
}).then(function(res){
console.log(res);
}).catch();
This works for me.
Facing CORS in angular, when i was trying to make a API call between my localhost to another domain.I am getting 404 issue .
1.Front End : Angualr 7
Front end request part:
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': 'true',
'Access-Control-Allow-Methods':'POST',
'Access-Control-Allow-Headers': 'Content-Type'
})
}
login(username: string, password: string) {
return this.http.post<any>('http://remote/djaxtesting/enter_uiupgrade/index.php/api/v1/user/validate',
{acc_type: "ADMIN", uemail: "djax_admin#dreamajax.com", upw: "123456"},httpOptions)
.pipe(map(user => {}))
}
Back end coding :
<?php defined('BASEPATH') OR exit('No direct script access allowed');
header ("Access-Control-Allow-Origin: *");
header ("Access-Control-Allow-Credentials: true");
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');
header('Content-Type: application/json');
public function validate_post()
{
$role = array('ADVERTISER','TRAFFICKER','ADMIN','MANAGER');
if($this->post('acc_type') !='' and in_array($this->post('acc_type'),$role))
{
switch(strtoupper($this->post('acc_type')))
{
case "ADMIN":
$adminObj = $this->do_networks->validate_user($this->post('uemail'),$this->post('upw'),$this->post('acc_type'));
//$this->response($adminObj, 200);
}
}
}
enter image description here
We using php for api. Helping handing needs to solve this issue ?
The problem with the option method. Option request should be a 200 returning an empty response. Then the browser will send the real POST request.
for that replace with the headers in your PHP File in the constructor. It will work.
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method, Authorization");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
$method = $_SERVER['REQUEST_METHOD'];
if ($method == "OPTIONS") {
die();
}
This question already has answers here:
PHP Get JSON POST Data
(1 answer)
Reading JSON POST using PHP
(3 answers)
XMLHttpRequest cannot load XXX No 'Access-Control-Allow-Origin' header
(11 answers)
Closed 4 years ago.
I just created an angular 7 project
I try to send a post with some data, nothing is set in the header part
so on the server side I only get the php script called, nothing in the $_POST array
this code works fine in angular 5, I should see the data in the header log in chrome
createPostOptions() {
let headers = new Headers({
'Content-Type': 'application/json',
});
let options = new RequestOptions({ headers: headers, withCredentials: true });
return options;
}
getParts(): Observable<any>
{
return this.http.post('http://localhost/site/data.php',{command:'getParts'}, this.createPostOptions())
.pipe(map((response: Response) => {
return this.processData(response,this.router);
}));
}
php code:
function cors()
{
header("HTTP/1.1 " . "200" . " " . "OK");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header('Access-Control-Allow-Headers: Accept, Content-Type, Access-Control-Allow-Credentials, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Access-Control-Allow-Methods, X-Requested-With, X-API-KEY, X-Auth-Token, X-Requested-With, Authorization, Content-Range, Content-Disposition, Origin, Access-Control-Request-Method');
header('Access-Control-Max-Age: 86400');
header('Access-Control-Allow-Origin: '."http://localhost");
header('Access-Control-Allow-Credentials: true');
}
//-----------------------------------
if($_SERVER['REQUEST_METHOD']=="OPTIONS")
{
cors();
}
else
{
...
}
I should see something like this
Any help apreciated
Since you are sending json in the body, but not as post parameters, you need something like
$jsonInput = file_get_contents('php://input');
$obj = json_decode($jsonInput);
$command = $obj->command;
I have this funcion who list objects with arrays:
//onload event-- to set the values
$scope.$on('$stateChangeSuccess', function () {
$scope.cart=sharedCartService.cart;
$scope.total_qty=sharedCartService.total_qty;
$scope.total_amount=sharedCartService.total_amount;
});
I need get all datas and insert all (populate) in a database. I´m using MySQL and PHP.
Thanks.
You create a file let say its called save.php
In that file you will have something like
header("Access-Control-Allow-Origin: *");
Global $db;
$db = new PDO('mysql:dbname=databasename;host=localhost', 'dbuser', 'dbpassword');
if (isset($_SERVER['HTTP_ORIGIN'])) {
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400'); // cache for 1 day
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
exit(0);
}
$postdata = file_get_contents("php://input");
if (isset($postdata)) {
$request = json_decode($postdata);
$cart = $request->cart;
$total_qty = $request->total_qty;
$total_amount = $request->total_amount;
}
else {
echo "Not called properly!";
}
$query = $db->prepare("
INSERT INTO yourtable
(cart, total_qty, total_amount)
VALUES
(:cart, :total_qty, :total_amount)");
$query->execute(array(
':cart' => $cart,
':total_qty' => $total_qty,
':total_amount' => $total_amount));
And in your function in Angular (stateChangeSuccess) you make a post request on for example http://localhost:8080/save.php
$http.post(url, data, config)
.then(
function(response){
// success callback
},
function(response){
// failure callback
}
);