无法使用Angularjs执行CORS请求 [英] Can't perform CORS request using Angularjs

查看:107
本文介绍了无法使用Angularjs执行CORS请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写我的第一个AngularJS应用,但在Angular中遇到了CORS问题.尝试了回复中提到的内容,但仍然没有运气解决这个问题.

I am writing my first AngularJS app and have run into a problem with CORS in Angular. Have tried what was mentioned in this reply but still have no luck solving this.

JS代码(main.js)如下:

The JS code (main.js) is as follows:

var app = angular.module("app",[]);
app.config(['$httpProvider', function($httpProvider) {
    delete $httpProvider.defaults.headers.common['X-Requested-With'];
    }
]);

app.controller("AppCtrl", function ($scope, $http) {
    var postData = "username=demo&password=demo";
    $http.post("http://sampleurl.com/login",postData).success(function(data, status, headers, config)
    {
        console.log(data);
    });

});

Index.html文件为:

The Index.html file is:

<!DOCTYPE html>
<html>
<head>
    <title>Sample Angular App</title>
</head>

<body ng-app="app" ng-controller="AppCtrl as app">

<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular.min.js"></script>

<script src="main.js"></script>
</body>
</html>

我得到的错误如下:

Failed to load resource: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. 

我尝试使用Ajax运行此请求,并且与Ajax一起正常工作.由于某些原因,无法使用Angular使其正常工作.关于我在这里做错什么的任何想法吗?

I have tried running this request using Ajax and it works just fine with Ajax. For some reason can't get this to work using Angular. Any idea as to what I am doing wrong here?

谢谢!

推荐答案

好.因此,基本上经过一番修补之后,我意识到使用

Ok. So basically after alot of tinkering around I realised that params were not getting passed using

  $http.post("http://sampleurl.com/login",postData)

所以我重写了这个请求,如下所示:

So I rewrote this request as follows:

 $http({
    url:'http://sampleurl.com/api',
    method:"POST",
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    data: postData
  })

这得到了通过的要求.希望这对其他人有帮助.

This got the request to go through just fine. Hope this is of help to someone else.

干杯!

这篇关于无法使用Angularjs执行CORS请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆