Im working on a mobile app in Ionic2 and angular2 but im having difficulty retriving the proper data from the server. I made a simple php script on my website which should return/echo '1' when data is posted to the server however i retrieve the entire response instead. Below is what my home controller looks like currently.
import {Component} from "#angular/core";
import {Http} from "#angular/http";
#Component({
templateUrl: 'build/pages/home/home.html',
providers: [LocationMgr, HttpService]
})
export class HomePage {
dataRecv: any;
constructor(private http: Http)
{
let data = JSON.stringify({username: 'user'});
http.post('http://dsykes.esy.es/php/adb.php', data).map(res => res).subscribe(data => { console.log(data.data); this.dataRecv = data; });
}
}
Also, here is the php script I have aswell.
<?php
header("Content-Type: *");
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
echo 1;
?>
The only reason why Im using a POST response is because i plan of advancing my script and server requesting using POST for personal reasons. A GET Request would work fine but I need POST to return the return the data only.
I'm currently runniong on the 2.0.0-beta.32 version of ionic aswell.
Ahhh!!! Forgot to include the .json() function at the end of the response map! LOL
Related
I have this code:
login: any;
constructor(private http: HttpClient) { }
ngOnInit() {
this.http.get("http://localhost:8000/login/list")
.subscribe(
resultado => {
this.login = resultado;
document.write(this.login);
}
);
}
I tried to get data from a JSON located on the web and I got the data! However, when I try to get it from the localhost server (which is running a PHP application and returning JSON) it doesn't seems to work. I tried to open the URL on the web browser and it does actually return a JSON.
Any clue on what's going on?
Problem was CORS.
Adding this to my PHP project made it work:
composer req cors --ignore-platform-req=ext-http
This question already has answers here:
XMLHttpRequest cannot load XXX No 'Access-Control-Allow-Origin' header
(11 answers)
Closed 2 years ago.
I'm doing a ReactJS frontend App and get data from an API created with PHP Rest API, but my react is host on localhost:3000, but my php file is hosted on localhost:80. so not sure how to write the baseurl in react, cause it always got some error until now.
May I know how to solve it? Thank you.
error:
Access to XMLHttpRequest at 'http://localhost/reacttest/src/api/read.php' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
xhr.js:184 GET http://localhost/reacttest/src/api/read.php net::ERR_FAILED
ReactJS:
import React from 'react';
// import logo from './logo.svg';
import './App.css';
import axios from "axios";
const baseUrl = "http://localhost:80/reacttest/src/api";
const sampleGet = async () => {
const result = await axios.get(baseUrl + "/read.php");
console.log(result);
};
const samplePost = async () => {
const result = await axios.post(baseUrl + "/posts", {
sampleData: "nabezap"
});
console.log(result);
};
const sampleDelete = async () => {
const result = await axios.delete(baseUrl + "/posts/4");
console.log(result);
};
function App() {
return (
<div className="App">
<button onClick={sampleGet}>GET</button>
<button onClick={samplePost}>POST</button>
<button onClick={sampleDelete}>DELETE</button>
</div>
);
}
export default App;
read.php:
<?php
header('Content-Type: application/json;charset=utf-8');// all echo statements are json_encode
include('se.php');
include('db.php');
session_start();
$doctordb = new doctorModel; //instantiate database to start using
$result = $doctordb->showDoctorinfo();
if($result == false) {
http_response_code(204); // no content
} elseif(is_array($result)) {
http_response_code(200); //success
echo json_encode($result);
}
?>
api.php:
The base url is correct (80 is default) and if you check your network tab in dev tools, you’ll see the request did in fact go out and received the expected response.
The issue is with your REST API. The clue is in the error:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
This means the server received the request, processed it and returned a response— but it didn’t attach a Access-Control-Allow-Origin: ‘http://localhost:3000’ header. When your browser receives the response from the API, it checks for this header and refuses javascript access to the response data if it’s missing. This is normal.
Setting up CORS on your REST API is the way to go. What framework (if any) are you using? I’ll edit this answer with more info once I know.
I'm running a local angular 9 client in dev mode and attempting to post to a backend PHP resource. Initially, I was getting CORS problems, so in the PHP file, I added:
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");
and also started using a proxy on the client side:
{
"/awana-record-keeping/server/*": {
"target": "http://bridgewaycc.org/site",
"secure": false,
"changeOrigin": true,
"logLevel": "debug"
}
}
The CORS errors went away in the Chrome console. However, now I see the following sequence of network calls:
http://stevewarsa.com/all-calls.png
First there is a POST call, which results in a 301 response code (which I believe is coming from the local angular proxy):
http://stevewarsa.com/first-call.png
Second there is a GET call, which does not send a request payload and which results in a 200 response code:
http://stevewarsa.com/second-call.png
Third there is an OPTIONS call, which results in a 200:
http://stevewarsa.com/third-call.png
The result is that the PHP script does not receive the post data and therefore cannot return the requested data.
Note - the 3 calls shown in the network tab of Chrome are all resulting from one http post invocation in angular:
ngOnInit() {
this.awanaService.getClubbersByYear(<YearRange>{startYear: 2020, endYear: 2021}).subscribe(clubbers => {
console.log("Here are the clubbers:");
console.log(clubbers);
});
}
Here is the awanaService:
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { YearRange } from './year-range';
#Injectable({
providedIn: 'root'
})
export class AwanaService {
private _uri = "/awana-record-keeping/server/";
constructor(private httpService:HttpClient) { }
public getClubbersByYear(yearRange: YearRange) {
return this.httpService.post<string[]>(`${this._uri}get-clubbers-by-year-range.php`, yearRange);
}
}
I have used angular proxies in the past to do local development issuing http POST requests to remote servers hosting PHP, but for some reason, this time I cannot get around this issue.
Any ideas how to solve this?
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
I am working on Angular4 Project.
For testing, first I had done the get request to any json api and its worked well.
Now I am working to connect the php file and testing it. In test.php I had
echo "string";
Now in console I am getting this error:
XMLHttpRequest cannot load http://localhost/php-file/test/test.php.
No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:4200' is therefore not allowed
access.
I also attached screenshot of it. I had googled it but unable to get any solution for this.
then I had edited the test.php like below. Is it right way to do so?
<?php
header("Access-Control-Allow-Origin: *");
$data = ['news','dfdf','ddd'];
echo json_encode($data);
?>
This is how you need to do. You need to include headers in angular as well.
import { Http, Headers, Response, RequestOptions } from '#angular/http';
headers = new Headers();
requestOptions = new RequestOptions();
this.headers.append('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
this.headers.append('Cotent-Type', 'application/json');
this.requestOptions.headers = this.headers;
return this.http.post("http://localhost/php-file/test/test.php", this.requestOptions).map(res => res.json());
This is how you should make post request. Make sure to subscribe this call and then you can get data from return.
I hope it helps.