Angular 7 - http posts - no PAYLOAD sent inside headers [duplicate] - php

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;

Related

How to prepare $_POST in PHP with Redux Toolkit Query [duplicate]

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);

React - PHP: How to fix problem of CORS with fetch request for POST request?

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.

Troubleshooting missing "Authorization" request header in PHP

I'm currently working on a PHP REST API for a uni project, which uses JSON web tokens passed from mobile web applications using PhoneGap, or my desktop during development.
When sending the token to my server page "friends/read.php" using ajax, the server was picking up the Authorization header correctly with
$headers = getallheaders();
$authHeader = $headers['Authorization'];
but stopped doing so after several successful runs. After that point, the header is no longer being picked up.
My request code is as follows:
$.ajax({
url: "http://localhost/chordstruck/api/friends/read.php",
type: "GET",
beforeSend: function (request) {
request.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('jwt'));
},
datatype: "json",
success: function (response) {
console.log(response);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
}
});
Oddly enough, when killing the PHP script prematurely with die("test") and then removing die() again, the server will then start picking up the Authorization header for several more requests.
Read.php:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 'on');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET');
header('Access-Control-Allow-Headers: Origin, Content-Type, Authorization, X-Auth-Token');
$config = require_once '../config/core.php';
require_once '../config/jwt_helper.php';
// get database connection
include_once '../config/database.php';
// instantiate profile object
include_once '../objects/profile.php';
$headers = getallheaders();
$authHeader = $headers['Authorization'];
$token;
if ($authHeader) {
list($jwt) = sscanf((string)$authHeader, 'Bearer %s');
if ($jwt) {
try {
$key = $config['jwt_key'];
$token = JWT::decode($jwt, $key, array('HS512'));
} catch (Exception $e) {
header('HTTP/1.0 401 Unauthorized');
exit();
}
} else {
header('HTTP/1.0 400 Bad Request');
exit();
}
} else {
header('HTTP/1.0 400 No Header Found');
exit();
}
echo "success";
?>
I have been encountering a CORS issue while developing this project, which I've countered with the above headers along with the following in my .htaccess file:
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
</IfModule>
Could this potentially be related? Any help/ideas would be greatly appreciated!
The problem appears to have been indeed related to CORS and after trying a multitude of approaches, the following solution is now working.
Replacing my headers in read.php with:
// Allow from any origin
if (isset($_SERVER['HTTP_ORIGIN'])) {
// Decide if the origin in $_SERVER['HTTP_ORIGIN'] is one
// you want to allow, and if so:
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']))
// may also be using PUT, PATCH, HEAD etc
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);
}
Credit goes to slashingweapon who used it to answer CORS with php headers

Angular cross origin issue in API call Backend PHP?

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();
}

php api rest does not accept cors requests even using header ('Access-Control-Allow-Origin: *');

I'm creating an angular application 6 and api rest in php.
when my angular application tries to perform a request the following url: http://localhost/bdevApi/api/index/categoryexame?page=1
the following error is loaded:
Failed to load Response to preflight request doesn't pass access
control check: No 'Access-Control-Allow-Origin' header is present on
the requested resource. Origin 'http://localhost:4200' is therefore
not allowed access.
The angle is in port 4200 and my api is in 80
I visualized some tutorial and added the following header to my api
api/index.php
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');
include("config/config.php");
include("import/Interpreter.php");
include("import/SendJson.php");
include("database/Connection.php");
include("import/AuthToken.php");
$db = Connection::getInstance();
if( $db->getStateConnection() )
{
$arrayHeader = getallheaders();
$token = isset($arrayHeader["token"]) ? $arrayHeader["token"] : "";
// Recupera dados via Json
$strJson = file_get_contents('php://input'); //echo $strJson;
$jsonObject = json_decode($strJson); //var_dump($strJson);
$Interpreter = new Interpreter(
"http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]",
$_SERVER['REQUEST_METHOD'],
$jsonObject
);
if(AuthToken::validateToken($token))
$Interpreter->initializes(true);
else
{
if($token == "")
$Interpreter->initializes(false);
else
{
$S = new SendJson();
$S->Send("200", "1", "Token não autenticado", null);
}
}
$db->closeConnection();
}
?>
How do I get my application to accept these headers and not show this error?
[EDIT]
[]1
new error
Failed to load
http://localhost/bdevApi/api/index/categoriaexame?page=1: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:4200' is therefore not allowed
access.
This is happening because of cross origin policy. You can go through this document to get the details knowledge about CORS:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Server-Side_Access_Control
You can try this code below:
// Allow from any origin
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);
}

Categories