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.
Related
Given the following code:
fetch(mockproxy+myphp.php,{
method: 'POST',
headers:{'Token':token["token"]},
body: name,
}).then((response) => response.json())
.then((json)=>{
toast.success(JSON.stringify(json));
})
.catch((err) => {
toast.error(JSON.stringify(err));
})
}
mockproxy is helping bypass CORSS. The file looks like this:
const corsAnywhere = require('cors-anywhere');
const express = require('express');
const apicache = require('apicache');
const expressHttpProxy = require('express-http-proxy');
const CORS_PROXY_PORT = 5000;
// Create CORS Anywhere server
corsAnywhere.createServer({}).listen(CORS_PROXY_PORT, () => {
console.log(
`Internal CORS Anywhere server started at port ${CORS_PROXY_PORT}`
);
});
// Create express Cache server
let app = express();
// Register cache middleware for GET and OPTIONS verbs
app.get('/*', cacheMiddleware());
app.options('/*', cacheMiddleware());
// Proxy to CORS server when request misses cache
app.use(expressHttpProxy(`localhost:${CORS_PROXY_PORT}`));
const APP_PORT = process.env.PORT || 5080;
app.listen(APP_PORT, () => {
console.log(`External CORS cache server started at port ${APP_PORT}`);
});
/**
* Construct the caching middleware
*/
function cacheMiddleware() {
const cacheOptions = {
statusCodes: { include: [200] },
defaultDuration: 60000,
appendKey: (req, res) => req.method
};
let cacheMiddleware = apicache.options(cacheOptions).middleware();
return cacheMiddleware;
}
And the server is a shared server where I upload the PHP files so they can access to the DB. The php receives the data and give a response when I use postman but not when I execute the fetch from the dev website, I'm using react, I think it doesn't matter in this case.
The PHP file:
<?php
$headers = apache_request_headers();
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');
$method = $_SERVER['REQUEST_METHOD'];
if ($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");
exit;
}
if (isset($_POST["name"])) {
echo json_encode(" name" . $_POST["name"]); //returned on postman
}else{
echo json_encode("no name"); //returned on development.
}
exit;
So this is a code i use when i want to fetch all data from a form. You can obviously not loop through all forms like i do below but just your single form.
// Query all forms in the DOM or a specific one if you want
const forms = document.querySelectorAll('form');
// Loop through them
forms.forEach((form) => {
// if method is post
if (form.method === 'post') {
form.addEventListener('submit', (event) => {
// prevent default submit
event.preventDefault();
// prepare the data
let data = new FormData(form);
// fetch using the form's
fetch(form.action, {
method: 'post',
body: data,
})
// get the text() from the Response object
.then(response => response.text())
.then(text => {
// Display it in the result div
document.getElementById('result').innerHTML = text;
})
}, false);
// if not post (get really)
} else {
form.addEventListener('submit', (event) => {
// prevent default submit
event.preventDefault();
// build the URL query params from the submitted data
const data = new URLSearchParams(new FormData(form).entries());
// Fetch, URL is formed from the action, append ? and then the query params
fetch(form.action + '?' + data)
// get the text() from the Response object
.then(response => response.text())
.then(text => {
// Display it in the result div
document.getElementById('result').innerHTML = text;
})
}, false);
}
});
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.
After hours of trying is still can't get my React Expo application (localhost http://192.168.1.113:19006/#/) to connect to my PHP api that is hosted on an external server.
The header of my api file's is as following;
header("Access-Control-Allow-Origin: *");
//header("Access-Control-Allow-Headers: *");
//header("Access-Control-Allow-Credentials: 'true'");
header("Content-Type: application/json");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
When I use postman to connect and test mine /login.php file with the following json body;
POST to: www.URLofAPIlocation.nl/subFolder/api/login.php
{
"email" : "info#email.nl",
"password" : "Password12345"
}
The api returns the JWT token and succes message as expected.
{
"message": "Successful login.",
"jwt": "eyJ0eXA..... ( FULL TOKEN )"
}
But when I try to connect with the following functions within my react native application it try to uses the localhost base url and not the given;
async function postData(url = '', data = {}) {
const response = await fetch(url, {
method: 'POST',
mode: 'cors', // Without cors it fails.
cache: 'no-cache',
// credentials: 'same-origin', // Not sure if needed.
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST',
'Access-Control-Max-Age':' 3600',
},
redirect: 'follow',
referrerPolicy: 'no-referrer',
body: JSON.stringify(data)
});
return await response.json();
}
// https://www.URLofAPIlocation.nl/... and https://URLofAPIlocation.nl/ also not working
function login(){
postData('www.URLofAPIlocation.nl/subFolder/api/login.php', {
email : "info#email.nl",
password : "Password12345",
})
// Other option without error catching. (not working..)
// .then((data) => {
// console.log(data); // JSON data parsed by `response.json()` call
// });
.then(response => {
console.log(response)
return response.json()
})
.then(response => {
console.log("End query"+ response);
return response;
})
.catch(err => {
console.log("Error: "+err)
});
}
I'm not sure what I do wrong since every tutorial and documentation I find the exact same setup as I am using.
The error message is as following;
POST http://192.168.1.17:19006/www.URLofAPIlocation.nl/subFolder/api/login.php 404 (Not Found)
It seems like that react expo uses it's own location as the base url and adds the url of the fetch after it. The location of the api is off course without: http://192.168.1.17:19006//. I can't find where to change or remove this, so help would much be appreciated.
Thanks in advance!
Ps because of personal reasons I've hidden the exact web address of the api location and passwords. The api is hosted on an https domain and functions as expected.
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();
}
I'm trying to do a simple POST from angularjs to a dummy php file to understand how this works.
Here in my angularjs part:
<html ng-app="loginApp">
<head>
<meta charset="utf-8">
<title>Login</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<script>
var logindata = {username:'abc', password:'abc'}
var loginApp = angular.module('loginApp', []);
loginApp.controller('loginCtrl', function ($scope, $http){
var request = $http({
method: "POST",
url: "http://different-ip/a.php",
data: logindata,
headers: { 'Content-Type': 'multipart/form-data', 'Authorization': 'Basic ' + btoa(logindata.username + logindata.password),
'Access-Control-Allow-Origin': "*"}
});
request.success(
function( data ) {
$scope.someVariableName = data;
}
);
});
</script>
</head>
<body ng-controller="loginCtrl">
<h2>Angular.js JSON Fetching Example</h2>
<p> {{ someVariableName }} </p>
</body>
</html>
Here is my PHP part (a.php) that resides on http://different-ip
<?php
header("Access-Control-Request-Method: *");
header("Access-Control-Request-Headers: *");
header("Access-Control-Allow-Origin: *");
file_put_contents("aa.txt", json_decode(file_get_contents('php://input'),true));
file_put_contents("aaa.txt", getallheaders());
?>
When I execute my angularjs file, the chrome console gives me this error:
Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers in preflight response.
When I try doing a post to this a.php using Postman, everything works fine. So why is angularjs not allowing it?
I've tried to read about CORS and there is no straightforward answer to how this issue can be resolved (code wise). Can someone please help me out? Thanks in advance.
Added this instead of current headers to my PHP file and now it works! Thanks #Armen for your help!
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);
}
Add this 3 headers at top of a.php instead current ones with if condition
<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization");
if($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
header( "HTTP/1.1 200 OK" );
exit;
}
file_put_contents("aa.txt", json_decode(file_get_contents('php://input'),true));
file_put_contents("aaa.txt", getallheaders());
?>
You can check more about CORS here: http://www.w3.org/TR/cors/#access-control-allow-headers-response-header
Postman works because it is additional browser extension which don't cares about headers policy and don't check it before request.