I'm simply trying to get POST parameters on my PHP server, sent from my ReactJS app. In the server response, I can see that 'myParameter' is null. I think this is because of the Cross Origin issue, but I've tried many suggestions from answers to similar questions and nothing I've tried has worked. I believe that I'm looking for the proper code to add to my PHP file. It's been days now of this issue and I'm hoping someone here can help.
Background information (in case it matters at all). My PHP file is on my server hosted with hostgator. GET requests with URL parameters work perfectly, but POST parameters seem to be blocked. I'm trying to send more data than the URL option allows.
Thank you so much!
ReactJS Code:
axios.post('https://mywebsite.com/endpoint.php', {
myParameter: 'test',
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
PHP Code:
<?php
header("Access-Control-Allow-Origin: *");
echo json_encode($_POST['myParameter']);
?>
I also tried this, but it did not change the result:
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
header('Access-Control-Max-Age: 86400');
echo json_encode($_POST['myParameter']);
?>
EDIT:
Based on the answer from the post linked by Aaqib, I was able to successfully get the data on my server!
i usually prefer the axios constructor with properties. its much more clearer then the short hand methods.
axios({
method:'POST',
url:'https://mywebsite.com/endpoint.php',
headers:{},
data:{
myParameter: 'test'
}
}).then((res)=>{})
.catch((err)=>{});
Try this and see if it works.
axios.post('https://mywebsite.com/endpoint.php', {data: {
myParameter: 'test'
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
Related
I am trying to make a login validation form in React and i am using axios to make database calls.
The thing is, i make contact with the server - i get 200 response but the data i post is not there.
This is what i did the first time:
const user = {username: this.state.username, password: this.state.password}
axios.post("http://localhost:80/thinksmart/post_requests/login.php", user)
.then(res => console.log(res))
.catch(err => console.log(err))
Then i tried another approach - where i set up base url :
const api = axios.create({baseURL: 'http://localhost:80'})
api.post("/thinksmart/post_requests/login.php", user)
.then(response => {
console.log(response)
})
.catch(error =>
console.log(error)
)
and neither of these worked.
In PHP i only do this:
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');
echo json_encode($_POST);
and i get an empty array even though i have data sent (the user data)
You can solve this issue in two ways:
1- PHP code changes: to get the JSON data in the backend you need to execute the following code instead of the $_POST:
$json = file_get_contents('php://input');
2- Javascript code changes: To be able to receive the data in the backend using $_POST you need to send it using FormData more details can be found in the following link:
axios post requests using form-data
http://www.hakvik.se/react/#/contact
I have googled for several days without success. No cors problems. Everything looks okay in console but nothing goes to db table on my live host when I am trying to post data from my contact form to mysql db. When I change details in Headers and axios call to locahost it works as expected.
Below is the relevant code, please tell me if you need additional code to see the problem!
I have used create-react-app.
handleSubmit = (event) => {
event.preventDefault();
let config = {
headers: {
'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept',
'Access-Control-Allow-Origin': 'http://www.hakvik.se',
'Content-Type': 'application/x-www-form-urlencoded',
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE',
}
};
// axios.post('http://127.0.0.1/myProjects/react-refactored-with-redux/src/api/index.php/?/user',
axios.post('http://www.hakvik.se/react/#/src/api/index.php/?/user',
querystring.stringify({
fname: this.state.fname,
lname: this.state.lname,
mail: this.state.mail,
msg: this.state.msg
}),
config
);
This scenario uses Access-Control-Allow-Credentials alongside the POST method to manage server-side PHP session variables that must remain intact.
For reference, the front-end is a create-react-app project running at http://localhost:3000 and the back-end is PHP running on example.com.
Achieving this with the $.ajax() method is easy and straightforward.
UseAjax(incomingData) {
return new Promise(function(resolve, reject) {
$.ajax({
url: 'http://example.com/api.php',
type: 'post',
data: incomingData,
xhrFields: { withCredentials: true },
success: function(data) {
console.log(data)
}
})
.then((data,status) => {
// Get the result and transform into valid JSON
if ( typeof data === typeof 'str' ) {
try {
data = JSON.parse(data);
} catch(e) {
reject(data,status);
console.log('Exception: ', e);
console.log('API Returned non-JSON result: ', data);
}
}
return data;
}).then((dataObject) => {
console.log('dataObject:');
console.log(dataObject);
resolve(dataObject);
});
});
}
Oddly enough though, when using the fetch() API, it is under the impression that I am not allowing CORS. Of course I have CORS enabled as this request works fine with Ajax and only fails while using the fetch() API.
Here is a look at what I tried while using the fetch() API.
UseFetch(requestData) {
return new Promise(function(resolve, reject) {
console.log('Relay() called with data: ', requestData);
fetch('http://example.com/api.php', {
method: 'POST', // or 'PUT'
body: JSON.stringify(requestData), // data can be `string` or {object}!
headers: new Headers({
'Content-Type': 'application/json'
})
}).then((result) => {
// Get the result
return result.json();
}).then((jsonResult) => {
// Do something with the result
if ( jsonResult.err )
reject(jsonResult);
console.log(jsonResult);
resolve(jsonResult);
});
});
}
It provides this error.
Failed to load http://example.com/: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
On the PHP side, I am using a simple output to ensure nothing else is going wrong causing the error on the server's side.
<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: http://example.com');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type, Authorization, x-requested-with');
echo json_encode(['data'=>'result']);
?>
I have followed many questions, but most notably this question with a very thorough explanation of the issue and possible solutions.
For now, I am just using the tried-and-true $.ajax() to complete this task, but I am wanting to fully understand the fetch() API to the extent necessary to replicate this functionality as it seems like something very basic from my experience.
In your PHP code, you've specified header('Access-Control-Allow-Origin: http://example.com');. This is wrong - you need to specify the value passed in the Origin request header (which in your case would be http://localhost:3000):
header('Access-Control-Allow-Origin: http://localhost:3000');
Ideally you wouldn't hardcode it - you'd just extract the Origin request header and pass that back.
BTW, I believe that JQuery's $.Ajax uses fetch() under the covers (just like XmlHTTPRequest()). Basically, everything uses fetch...
I am trying to create mobile application in ionic framework, for that I have to use CROS with angular js application working on localhost:8100. The server side of this application is hosted and working under PHP framework Laravel. For cross-origin request I have set up following headers in Laravel filter.php
App::before(function($request){
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content- Type, Access-Control-Allow-Origin');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Allow-Credentials: true');
});
When I am trying to post some data on a url, getting an error reason CORS preflight channel did not succeed. My angular js script is given below.
var url = http://example.com/location
var postdata = {some : “data”};
$http.post(url, postdata)
.success(function (data) {
// Some success code
})
.error(function (data) {
// Some failed code
});
Run a post request through postman and you should see a verifycrsf token error. You can get through this by editing the verifycrsf.php file in your Laravel file, add your paths to the function there and it should work.
Example: 'api/*' for example.com/api/matric
I'm a long time overflower and eventually signed up.
I've gone through tons of threads but none could help me with my problem.
I am about to create a RESTful API with the slim framework in php and have problems with the crossdomain put requests.
Let me give you a quick introduction to what I've done.
After wrtining the first GET requests I was looking for a method to test my API easily and found the "RESTClient" Firefox addon, it worked well so I continued using it.
After a few tests I tested a self-written code on another server and there the problem occured.
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at %1$S. (Reason: CORS preflight channel did not succeed).
What I wonder the most about is the fact that the Firefox addon had no problem to make the request at any time, it always showed the expected response. The error above just occured when I tried to send a request by my own code. I read a lot about cross-origin requests but nothing helped me, I hope you can.
Now first of all let me show you my slim framework php code
<?php
header('access-control-allow-origin: *');
header('Content-Type: application/json');
function output($arr){
echo json_encode($arr);
exit;
}
require 'Slim/Slim.php';
\Slim\Slim::registerAutoloader();
$app = new \Slim\Slim();
$app->put(
'/put',
function () {
$output = array("status"=>"200","message"=>"This is a put test");
output($output);
}
);
$app->run();
?>
And my test.html
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<script type="text/javascript">
(function($) {
var url = 'URL';
$.ajax({
type: 'put',
url: url,
async: false,
crossDomain:true,
dataType: 'json',
success: function(json) {
console.log(json);
},
error: function(e) {
console.log(e.message);
}
});
})(jQuery);
</script>
</body>
</html>
Can someone please explain to me how I can get this PUT request working. I am really in this despair mood right now. I understand all that cross-domain topic but why is he not letting it go after i set the access-control-allow-origin in the php code ? What is the firefox addon doing different? ...
It seems that you forget to add methods in the header.1
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');