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
Related
I stumbled upon a problem when running my Flutter app on my real device. I tried running it with an emulator and it works just fine (i.e. it communicates with my localhost Laravel server), but upon running it on my phone/real device, Flutter just stops interacting with the localhost server altogether. Below is a snippet of my code.
Future<List> _login() async {
if (user.text.isEmpty || pass.text.isEmpty) {
Alert(context: context, title: "Incorrect Data", type: AlertType.error)
.show();
} else {
final resp =
await http.post("http://10.0.2.2:8000/api/login", headers: {
'Accept': 'application/json',
}, body: {
"username": user.text,
"password": pass.text,
}).catchError((error) {
print(error);
});
// resp is null since the app doesn't make any request to the server,
// thus calling statusCode throws an error
if (resp.statusCode != 200) { ... } else { ... }
}
I've made sure that android:usesCleartextTraffic="true" has been included in my AndroidManifest.xml and have been using 10.0.2.2 instead of the default 127.0.0.1, I've also made sure that the API's url works as intended using Postman. But it still gives me the same result. Any help would be appreciated!
Thank You!
I am writing an Angular app that calls php scripts hosted via xampp server. Instead of getting the response, the code from the script was returned instead.
I have setup the proxy as such:
// proxy.conf.json
{
"/api/*": {
"target": {
"host": "localhost",
"protocol": "https:",
"port": 4433
},
"secure": false,
"changeOrigin": true,
"logLevel": "debug"
}
}
Within another script, I could make a call to a php script using api/* path.
// test.service.ts (snippet)
#Injectable({
providedIn: 'root'
})
export class DatabaseService {
private httpOptions: Object = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
}),
responseType: 'text'
}
getData(): Observable<any> {
return this.http.get<any>('api/test-get.php', this.httpOptions)
.pipe(
retry(1),
catchError(this.errorHandle)
);
}
}
The responseType was set to text because I am expecting a simple string from the script.
// test-get.php
<?php
echo 'test';
?>
This script is located at api\test-get.php, relative to the root folder of the xampp server folder.
Issue now is that the response is printing out the code in test-get.php, instead of test. If I directly access https://localhost:4433/api/test-get.php, I would be able to see the echoed response.
I've read through some pages such as Angular-CLI proxy doesn't work, but I don't believe the issues are related to mine.
Hopefully I can get some help in figuring out what I'm missing here. Thanks in advance.
I've got a very strange issue.
local hosted PHP Slim App using XAMPP (localhost:4040)
local hosted Angular 4 App using CLI (localhost:4200)
Making API Requests using "Postman" and browser is no problem, everything works fine.
Now I'm integrating the requests into my Angular app using import { Headers, Http } from '#angular/http'; and observables.
const requestUrl = 'http://localhost:4040/register';
const headers = new Headers({
'content-type': 'application/x-www-form-urlencoded'
});
this.http
.get(requestUrl, {headers: headers})
.map(response => response.json())
.subscribe(result => {
console.log(result);
}, error => {
console.log(error);
});
The request always fails with:
Failed to load http://localhost:4040/register: 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:4200' is therefore not allowed access.
But: I am definitely sending these headers!
public static function createJsonResponseWithHeaders($response, $requestedData)
{
// Add origin header
$response = $response->withHeader('Access-Control-Allow-Origin', '*');
$response = $response->withHeader('Access-Control-Allow-Methods', 'GET');
// Add json response and gzip compression header to response and compress content
$response = $response->withHeader('Content-type', 'application/json; charset=utf-8');
$response = $response->withHeader('Content-Encoding', 'gzip');
$requestedData = json_encode($requestedData, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK | JSON_PRETTY_PRINT);
$response->getBody()->write(gzencode($requestedData), 9);
if (!$requestedData || (count($requestedData) === 0)) {
return $response->withStatus(404)->write('Requested data not found or empty! ErrorCode: 011017');
}
return $response;
}
What I already tried for solving:
Run Slim App inside a Docker Container to get a different origin than localhost - same behaviour
Add allow-origin-header right on top of the index.php
header('Access-Control-Allow-Origin: *'); - same behaviour
Your requests are blocked because of CORS not being set up properly. There are other questions that address this, e.g. How to make CORS enabled requests in Angular 2
What you should ideally look at using is a proxy that forwards your requests to the API, the latest Angular CLI comes with support for a dev proxy (see https://github.com/angular/angular-cli/blob/master/docs/documentation/stories/proxy.md) out of the box. You set it up with a proxy.conf.json that could look like this:
{
"/api": {
"target": "http://localhost:4040",
"secure": false,
"pathRewrite": {"^/api" : ""}
}
}
What this piece of code does is any requests from Angular to a URI matching /api will be forwarded to localhost:4040.
Note that you will also need to figure out how your app will talk to the API server in a non-dev environment. I have been happy with using Nginx to serve Angular files, and act as proxy for the API.
Sorry, my bad. The solution is simple:
The "Cache-control" header in the request seems to be not allowed, although it worked fine when testing the api with Postman.
I removed the header from the request and everything worked well.
I'm having a problem when I receive my JSON in a React Native app.
I'm doing a simple fetch request to get it
getApplicationList()
{
return fetch('http://192.168.X.X/index.php')
.then((response) => response.json())
.then((responseJson) => {
return responseJson;
})
.catch((error) => {
return 'There has been a problem with your fetch operation: ' + error.message;
});
}
but when I make a console.error(getApplicationsList()); in the render function, I'm getting a very bizarre log on the android emulator:
console.error: {"_40":"0","_65":"0","_55":"null","_72":"null"}
In my PHP file, I'm returning a JSON encoded response, and when I type my URL (with 'localhost') in the navigator I can get it.
When I launch the app from the emulator, I change the localhost adress with my computer IP, and when I type this URL in the browser, I'm getting a Cannot GET /index.php response. I don't know if it's alright, and I'm feeling a little lost between all of this.
Many thanks for your help
I found a solution using a real android device:
I followed this to make a new port for my device: Connect an Android Device To a Web Service on Local Host (the answer using the Chrome navigator settings)
and then I made my HTTP request in the app using the IP address of my computer with the port I typed in the previous link. And it worked.
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