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
Related
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
);
I’ve been trying to use the HttpClient module and it’s working like a charm for get a json file. However, i try to post data in a php script in my ionic project (src/assets/scripts/php/news.php).
src/assets/scripts/news.php :
header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']);
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
header('Access-Control-Max-Age: 1000');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
$postdata = file_get_contents("php://input", true);
src/pages/news/news.ts :slight_smile :
sendNewsToPhp(news: string){
//let data = JSON.stringify(news);
let data = news;
this.http.post("../assets/scripts/php/news.php", data, {headers: {'Content-Type': 'application/json'}})
.subscribe(
response => console.log("Res provider :", response),
error => console.log("err : ", error)
);
}
error :
error: "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<title>Error</title>\n</head>\n<body>\n<pre>Cannot POST /assets/scripts/php/news.php</pre>\n</body>\n</html>\n"
headers: Object { normalizedNames: Map(0), lazyUpdate: null, lazyInit: lazyInit()}
message: "Http failure response for http://localhost:8100/assets/scripts/php/news.php: 404 Not Found"
name: "HttpErrorResponse"
ok: false
status: 404
statusText: "Not Found"
url: "http://localhost:8100/assets/scripts/php/news.php"
I already tried :
http://localhost:8100/assets/scripts/php/news.php
http://myip:8100/assets/scripts/php/news.php
I think the problem is that my file is in my ionic project. Is it possible to do that?
To know -> i can't access to my php file with url.
I think you make one misunderstand there.
PHP working on Apache/Ngix service at port 80, not the ionic serve port, are you think right?
In fact, we usually has a separate web service as data provider, so our request url often like this.http[get/post/put/delete]('http://server.domain/api/your-page.php', data)
You can update angular config by proxy section slove it, but the proxy settings looks not working after package it to App, so my code is update url = baseUrl + url; before send it.
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);
});
I'm having some troubles to upload files and data to my server using Angular 2 and PHP.
I've followed this File Upload In Angular 2? to upload the data and file from Angular 2 and all seems to be OK (I can see the data received by printing php://input). My Angular 2 code is something like this:
upload(data: data, file: File): Observable<any> {
let header = new Headers();
header.append('Content-Type', 'multipart/form-data');
header.append('Accept', 'application/json');
let options = new RequestOptions({ headers: header });
let formData:FormData = new FormData();
formData.append('file', file, file.name)
formData.append('data', JSON.stringify({data}));
return this.http
.post('myurl', formData, options)
.map(response => {
return response;
})
.catch(error => Observable.throw(error.message || error));
}
The problem is that the superglobals $_POST and $_FILES aren't populated, so I can't access them (and the data and file uploaded so). I have the same problem when uploading only data and I solved it manually-populating the $_POST superglobal by doing
$_POST = file_get_contents("php://input");
but here I can't do this because of the $_FILES....
I see in this post PHP - empty $_POST and $_FILES - when uploading larger files that the problem could be that post_max_size or upload_max_filesize are small, but I set them to 100M (enought for my purposes) and still the same. Even I toured memory_limit higiher but nothing.
I think that my problem have to be in my server side, could be the headers I set or some configuration I missed. I discarded any CodeIgniter issue (I'm using last version of CodeIgniter) because I tryed to post to a simple php file and I have the same problem. The simplest server side I'm used is:
<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header('Access-Control-Allow-Headers: Content-Type');
exit(var_dump($_POST, $_FILES));
?>
But I get empty arrays...
Does anybody have any idea of what can I do?
I finally have found the solution to this problem.
In non-technical speaking (I'm not an expert), an htpp post multipart/form-data request use a boundary random string to identify the different parameters sent by the client in order to give the server a reference to parse the input. A valid request header looks like this:
Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryYnNrniY34QSJ48LC
In my implementatation, when setting the request header as:
header.append('Content-Type', 'multipart/form-data');
no boundary is set so PHP can't parse the input to populete $_POST and $_FILES. I tried to define my own boundary by appending at the end of the header but it didn't work. But... The solution is even easier: there is no need to specify the Content-Type header, Angular 2 will make it by only passing the data as FormData and performing a post request, creating a valid boundary that PHP can use.
So, a valid code to do this is:
upload(data: data, file: File): Observable<any> {
let formData:FormData = new FormData();
formData.append('file', file, file.name)
formData.append('data', JSON.stringify({data}));
return this.http
.post('myurl', formData)
.map(response => {
return response;
})
.catch(error => Observable.throw(error.message || error));
}
When performing this post request, Angular 2 will add a valid boundary in the multipart/form-data header.
That's all.
If someone can add more technical details about this, it would be great.
Hope this could help someone else.
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