Angular 2 Http Post Request中的混乱 [英] Confusion in Angular 2 Http Post Request
问题描述
首先.请忍受我的问题.
First of all. Please bear with my questions.
我正在做的只是执行ajax请求,该请求将返回字符串的响应数据.
What I am doing is just performing an ajax request which will return a response data of string.
这是我的PHP
<?php
header('Access-Control-Allow-Origin: *');
echo 'Peenoise Crazy';
?>
Http请求
let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
let options = new RequestOptions({ headers: headers });
return this.http.post('./app/parsers/peenoise.php', '', options)
.then(val => console.log(val))
这不起作用.但是,如果我将网址更改为以下 http://localhost:8912/app/parsers/peenoise.php
.可以.
This doesn't work. But if I change the url into this http://localhost:8912/app/parsers/peenoise.php
. It works.
问题
- 为什么
./app/parsers/peenoise.php
不起作用? - 如果我将网址更改为
http://localhost:8912/app/parsers/peenoise.php
.为什么需要放置header('Access-Control-Allow-Origin:*')
?它在我的应用程序的同一文件夹中. - 如何使用http.post而不传递
http://localhost:8912/route/to/phpfolder.php
的网址?
- Why
./app/parsers/peenoise.php
doesn't work? - If I change the url to
http://localhost:8912/app/parsers/peenoise.php
. Why do I need to putheader('Access-Control-Allow-Origin: *')
? It is on the same folder of my app. - How to use http.post without passing an url of
http://localhost:8912/route/to/phpfolder.php
?
任何帮助将不胜感激.请指导我这一点.谢谢
Any help would be appreciated. Please guide me to this. Thanks
推荐答案
实际上Angular会寻找后端服务器来发布数据,所以想象一下您的发布请求如下所示
Actually Angular looks for a backend server to post the data, so Imagine in your post request is like below
this.http.post('./app/parsers/peenoise.php', '', options).then(val => console.log(val))
它将尝试在该位置发出发布请求想象您在localhost:4200上提供了角度服务
It will try to make the post request at the location imagine you are serving angular on localhost:4200
http://localhost:4200/app/parsers/peenoise.php
现在回答您的问题:
1) ./app/parsers/peenoise.php
不起作用,因为它实际上是试图从您的后端服务中找到它
1)./app/parsers/peenoise.php
doesn't work because it's actually trying to find it from your backend service
2)每当您向与当前站点所在服务器不同的其他服务器发出http请求时,都需要放置 header('Access-Control-Allow-Origin:*')
使用,如果不使用它将以 Connection_refused_Error
结尾.
2)You need to put header('Access-Control-Allow-Origin: *')
whenever you are making an http request to a different server than from the one which your site is currently using, if you don't use that you'll end up with Connection_refused_Error
.
3)如果您只想使用角度,则可以使用嘲笑Ackends, in-memory-web-api
3)If you want to use just angular then there are mockAckends, in-memory-web-api
使用嘲讽后端的示例是这里
An example using mockBackEnd is here
这篇关于Angular 2 Http Post Request中的混乱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!