首先.请忍受我的问题.
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))这不起作用.但是,如果我将网址更改为以下 localhost:8912/app/parsers/peenoise.php .可以.
This doesn't work. But if I change the url into this localhost:8912/app/parsers/peenoise.php. It works.
问题
任何帮助将不胜感激.请指导我这一点.谢谢
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
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中的混乱
发布评论