【问题标题】:net::ERR_CONNECTION_REFUSED with http post in angular2net::ERR_CONNECTION_REFUSED 与 angular2 中的 http 帖子
【发布时间】:2017-07-12 12:59:40
【问题描述】:

我收到以下 POST 请求错误:

发布http://127.0.0.1:port/v1/route2net::ERR_CONNECTION_REFUSED

GET 请求运行良好。 POST失败的可能原因是什么? testPost有错吗?
这是角度服务的一部分:

@Injectable()
export class SampleService {
    private _getUrl: string = 'http://<server-ip>/v1/route1';
    private _postUrl: string = 'http://127.0.0.1:<port>/v1/route2';
    constructor(private _http: Http) {}
    testGet() {
        return this._http.get(this._getUrl).map((response: Response) => response.json());
}
    testPost() {
        const headers = new Headers();
        headers.append('Content-Type', 'application/json; charset=utf-8');
        this._http.post(this._postUrl, JSON.stringify({'key1': 'value1', 'key2': 'value2'}), headers).subscribe(() => {}, err => console.error(err));
    }
}

【问题讨论】:

    标签: angular http-post


    【解决方案1】:

    我认为问题在于您如何将标头传递给请求。标头应包含在 RequestOptions 对象中。此外,您不需要对 JSON 对象进行字符串化,因为您将 Content-Type 设置为 JSON

    testPost() {
        const headers = new Headers();
        headers.append('Content-Type', 'application/json; charset=utf-8');
        const options = new RequestOptions({ headers: headers });
        this._http.post(this._postUrl, {'key1': 'value1', 'key2': 'value2'}, options)
                  .subscribe(() => {}, err => console.error(err));
    }
    

    【讨论】:

    • 现在错误已更改为OPTIONS http://127.0.0.1:port/v1/route2 net::ERR_CONNECTION_REFUSED。顺便说一句,我已经确认port 正在监听。
    【解决方案2】:

    嗯,没有端口=端口。您需要定义一个真实的端口。默认情况下它是 80 并且您的应用程序可能正在使用此端口运行,这就是 get 工作的原因。但是您在第二次调用中对端口的明确定义是问题所在。

    连接被拒绝意味着没有真正的应用程序处理您的请求。如果标头错误,我猜应用程序本身会引发(应用程序)错误

    【讨论】:

      【解决方案3】:

      可能有一些问题会导致此类错误

      • 如果您的系统不需要,请删除 IP 地址后面的端口号。
      • 如果您使用 PHP 或其他技术进行通信,则应更改 .htacces 文件中 Angular 项目的权限。

      【讨论】:

        猜你喜欢
        • 2016-04-29
        • 2019-12-23
        • 1970-01-01
        • 2021-12-16
        • 2017-03-05
        • 2016-07-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多