2016-11-22 70 views
0

我试图做一个nativescript.This远程服务器上一个简单的HTTP请求是我迄今为止:我在终端上Nativescript HTTP请求PHP

import { Component, ChangeDetectionStrategy } from '@angular/core'; 
import {request} from "http"; 


@Component({ 
selector: 'home', 
templateUrl: 'modules/home/home.component.html', 
styleUrls:['modules/home/home.component.css'], 
changeDetection: ChangeDetectionStrategy.OnPush 
}) 

export class HomeComponent { 
public name: string = "Mark"; 
public username: string = "jahflasher"; 
public custom_text: string = "This s a custom text field"; 

public makePOSTRequest() { 

    request({ 
     url: "http://www.url.com/nsschoolapp/getHomePage.php", 
     method: "POST", 
     headers: { "Content-Type": "application/x-www-form-urlencoded" }, 
     content: JSON.stringify({ Name: this.name, Username: this.username,  Text: this.custom_text }) 
    }).then(response => { 
     console.log(response.content); 
    }).catch(err => { 
     console.log("Error occurred " + err.stack); 
    }) 

} 


    ngOnInit() { 
     this.makePOSTRequest(); 
    } 
} 

现在在的console.log()这样的:

JS: <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"> 
    JS: <html><head> 
    JS: <title>403 Forbidden</title> 
    JS: </head><body> 
    JS: <h1>Forbidden</h1> 
    JS: <p>You don't have permission to access /nsschoolapp/getHomePage.php 
    JS: on this server.</p> 
    JS: <p>Additionally, a 404 Not Found 
    JS: error was encountered while trying to use an ErrorDocument to handle the request.</p> 
    JS: <hr> 
    JS: <address>Apache Server at www.url.com Port 80</address> 
    JS: </body></html> 

现在在PHP我有这样的:

<?php 

//http://stackoverflow.com/questions/18382740/cors-not-working-php 

if (isset($_SERVER['HTTP_ORIGIN'])) { 
    header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}"); 
    header('Access-Control-Allow-Credentials: true'); 
    //header('Access-Control-Max-Age: 86400'); // cache for 1 day 
} 

// Access-Control headers are received during OPTIONS requests 
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') { 

    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) 
     header("Access-Control-Allow-Methods: GET, POST, OPTIONS");   

    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) 
     header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}"); 
    //exit(0); 
} 


    header('Content-Type: application/json; charset=UTF-8'); 
    $arr = array('success' => true,"conent"=> $_POST); 
    echo json_encode($arr); 

?> 

我怎样才能解决这个问题?看来我无法到达远程文件。我没有权限。

回答

1

试试这个代码,而不是:

header('Access-Control-Allow-Origin: *'); 

在AngularJS我们使用$ sceDelegateProvider.resourceUrlBlacklist才能到服务器。在Angular 2中,您可以使用:

import {SafeResourceUrl, DomSanitizationService} from '@angular/platform-browser'; 

看看这篇文章! Angular2 unsafe resource URL in iFrame with DomSanitationService

+0

感谢您的回复,但我收到了同样的错误。 – jessiPP

+0

我最终甚至没有使用这个,但我从研究和尝试中学到了很多东西。 – jessiPP