我正在尝试使用nativescript在远程服务器上执行一个简单的http请求。

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);

?>


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

最佳答案

请尝试以下代码:

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

08-08 09:02