Angular js - Laravel CORS preflight channel did not succeed - php

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

Related

Cors enabled on php file, but still getting error

I'm building an API, for training purposes. I now have to send a POST request containing information. I'm using React JS and PHP, the problem is that everytime I send a request, the CORS error still shows up on the browser.
My JS file that sends the POST is, I changed the URL, because it's on my personal server:
axios.post('https://myurl/api/book/create.php', {
data: JSON.stringify(values, 0, 2)
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
and on the server side, I have the following
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
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");
With postman the request goes smoothly, but every single time sending through the browser
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://myurl/api/book/create.php. (Reason: CORS request did not succeed
Please make sure that you allow CORS in backend server. Then, you need send header for axios like following example
axios.defaults.headers.post['Content-Type'] = 'application/json';
axios.defaults.withCredentials = true;
axios.defaults.crossDomain = true;
(Or setting it in third paramenter after data)
You have to use either localhost or 127.0.0.1 for all the requests. In general in your code you should make calls to the server by just appending the URI to the current host, without re-adding the host and port in the URI string.
Answer based on: CORS request did not succeed

axios doesnt post data to server

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

Angular/HttpClient - How post data in a php file in my Ionic Project

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.

CORS work correctly on sharing host but not in localhost

I try to build a simple api base app with Laravel (as backend) and angularjs (as frontend).
In the beginning, I faced this error:
XMLHttpRequest cannot load http://127.0.0.1:8000/api/myroute. 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' is therefore not allowed access.
http://127.0.0.1:8000/api/myroute is my route to get some data, defined in Laravel as POST route.
That's while I've added the CORS middleware on my routes (according this sample) in this way:
Cors Middleware:
public function handle($request, Closure $next)
{
return $next($request)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
->header('Access-Control-Allow-Headers', 'x-requested-with, Content-Type, origin, authorization, accept, client-security-token');
}
and the below code is my $http code that I send request in Angularjs:
$http({
method: 'POST',
url: 'http://127.0.0.1:8000/api/myroute',
headers: {
'Content-Type': 'application/json'
}
}).then(function (response) {
console.log(response);
}, function (reject) {
console.log(reject);
});
I should to add this point that when I upload my project on a host, this Cors works Ok!
My problem is just http://localhost.
I also tried this in Firefox but the result was same, just Firefox not shown the Cross Origin Error and it's the only difference.
In this time I could not develop my project on host and I need to work locally.
So I need help!
Try to add below codes as header to your laravel's index.php file:
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, Authorization');
but be careful about cross origion!

CORS AJAX request from a NodeJS server to a PHP server

So I'm making an AJAX request from a node server to a PHP server. The PHP server looks like this:
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
echo json_encode($data);
The request is being sent via AngularJS list this:
app.controller('MainController', function($scope, $http) {
var req = {
method: 'POST',
url: 'http://testsite.com/api/login',
headers: {
'Content-Type': 'application/json'
},
data: {
Data : {
email: 'test',
}
}
}
$http(req)
.success(function(response){ console.log(response); })
.error(function(){ console.log("error")});
});
This works perfectly. The problem starts when I run this within an NodeJS app, everything is exactly the same except that the NodeJS with ExpressJS is running node bin/www. The error I get is:
Failed to load resource: the server responded with a status of 405 (Method Not Allowed)
Failed to load resource: Request header field Content-Type is not allowed by Access-Control-Allow-Headers
XMLHttpRequest cannot load http://testsite.com/api/login. Request header field Content-Type is not allowed by Access-Control-Allow-Headers
Any idea on what I could be missing?
Try adding this header in PHP server response
Access-Control-Allow-Methods: GET, POST
The client needs to know which methods the server can handle as part of the pre-flight request

Categories