标签: angularjs-http

如何在没有jQuery的情况下使用$ http发布urlencoded表单数据?

我是AngularJS的新手,一开始,我想只使用AngularJS开发一个新的应用程序.

我正在尝试使用$http我的Angular App 对服务器端进行AJAX调用.

为了发送参数,我尝试了以下方法:

$http({
    method: "post",
    url: URL,
    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
    data: $.param({username: $scope.userName, password: $scope.password})
}).success(function(result){
    console.log(result);
});
Run Code Online (Sandbox Code Playgroud)

这是有效的,但它也使用jQuery $.param.为了消除对jQuery的依赖,我尝试了:

data: {username: $scope.userName, password: $scope.password}
Run Code Online (Sandbox Code Playgroud)

但这似乎失败了.然后我尝试了params:

params: {username: $scope.userName, password: $scope.password}
Run Code Online (Sandbox Code Playgroud)

但这似乎也失败了.然后我尝试了JSON.stringify:

data: JSON.stringify({username: $scope.userName, password: $scope.password})
Run Code Online (Sandbox Code Playgroud)

我找到了这些可能的答案,但没有成功.难道我做错了什么?我相信,AngularJS会提供这个功能,但是如何?

javascript ajax jquery angularjs angularjs-http

191
推荐指数
4
解决办法
27万
查看次数

如何在AngularJs中启用CORS

我使用JavaScript为Flickr照片搜索API创建了一个演示.现在我将它转换为AngularJs.我在互联网上搜索,发现下面的配置.

组态:

myApp.config(function($httpProvider) {
  $httpProvider.defaults.useXDomain = true;
  delete $httpProvider.defaults.headers.common['X-Requested-With'];
});
Run Code Online (Sandbox Code Playgroud)

服务:

myApp.service('dataService', function($http) {
    delete $http.defaults.headers.common['X-Requested-With'];
    this.flickrPhotoSearch = function() {
        return $http({
            method: 'GET',
            url: 'http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=3f807259749363aaa29c76012fa93945&tags=india&format=json&callback=?',
            dataType: 'jsonp',
            headers: {'Authorization': 'Token token=xxxxYYYYZzzz'}
         });
     }
});
Run Code Online (Sandbox Code Playgroud)

控制器:

myApp.controller('flickrController', function($scope, dataService) {
        $scope.data = null;
        dataService.flickrPhotoSearch().then(function(dataResponse) {
            $scope.data = dataResponse;
            console.log($scope.data);
        });
    });
Run Code Online (Sandbox Code Playgroud)

但我仍然得到同样的错误.以下是我尝试的一些链接:

XMLHttpRequest无法加载URL.Access-Control-Allow-Origin不允许原点

http://samurails.com/tutorial/cors-with-angular-js-and-sinatra/

编辑:

我在@Quentin的建议下在node.js中创建了一个代理服务器:

var http = require('http');
var url = require('url');
var fs = require('fs');
var server;

server = http.createServer(function (req, res) {
    // your normal server …
Run Code Online (Sandbox Code Playgroud)

javascript cors angularjs angularjs-http

141
推荐指数
4
解决办法
36万
查看次数

使用AngularJS中的Promises成功/错误/ finally/catch

$http在AngularJs中使用,我不确定如何使用返回的promise并处理错误.

我有这个代码:

$http
    .get(url)
    .success(function(data) {
        // Handle data
    })
    .error(function(data, status) {
        // Handle HTTP error
    })
    .finally(function() {
        // Execute logic independent of success/error
    })
    .catch(function(error) {
        // Catch and handle exceptions from success/error/finally functions
    });
Run Code Online (Sandbox Code Playgroud)

这是一个很好的方法吗,还是有更简单的方法?

promise angularjs angularjs-http

111
推荐指数
5
解决办法
19万
查看次数

'Access-Control-Allow-Origin'标头包含多个值

我在客户端使用AngularJS $ http访问服务器端ASP.NET Web API应用程序的端点.由于客户端作为服务器托管在不同的域上,因此我需要CORS.它适用于$ http.post(url,data).但是只要我通过$ http.get(url)对用户进行身份验证并发出请求,我就会收到消息

The 'Access-Control-Allow-Origin' header contains multiple values 'http://127.0.0.1:9000, http://127.0.0.1:9000', but only one is allowed. Origin 'http://127.0.0.1:9000' is therefore not allowed access.

Fiddler告诉我,在成功的选项请求之后,get请求中确实有两个头条目.我做错什么地方在哪里?

更新

当我使用jQuery $ .get而不是$ http.get时,会出现相同的错误消息.所以AngularJS似乎没有问题.但哪里错了?

cors asp.net-web-api angularjs-http

93
推荐指数
7
解决办法
19万
查看次数

为什么不赞成AngularJS $ http成功/错误方法?从v1.6中删除了?

AngularJS文档有关于$http successerror方法的弃用通知.这个抽象是从库中删除的具体原因吗?

angularjs angularjs-http angularjs-1.6

56
推荐指数
1
解决办法
4万
查看次数

AngularJS没有检测到Access-Control-Allow-Origin标头?

我正在本地虚拟主机上运行角度应用程序(http://foo.app:8000).它正在使用另一个本地VirtualHost(http://bar.app:8000)发出请求$http.post.

$http.post('http://bar.app:8000/mobile/reply', reply, {withCredentials: true});
Run Code Online (Sandbox Code Playgroud)

在Chrome开发者工具的网络标签中,我当然会看到OPTIONS请求,并且响应中包含标题:

Access-Control-Allow-Origin: http://foo.app:8000
Run Code Online (Sandbox Code Playgroud)

但是,POST请求被取消,并出现以下错误:

请求的资源上不存在"Access-Control-Allow-Origin"标头.因此,不允许来源" http://foo.app:8000 "访问.

有没有人经历过这个?该Access-Control-Allow-Origin头非常清楚地包含在OPTIONS请求的响应,所以我不能为我的生命弄清楚为什么POST充当头不见了.

Access-Control-Allow-Credentials也设置为true.

angularjs angularjs-http

44
推荐指数
3
解决办法
16万
查看次数

AngularJS使用ng-upload上传图像

我正在尝试使用ng-upload在AngularJS中上传文件,但我遇到了问题.我的HTML看起来像这样:

<div class="create-article" ng-controller="PostCreateCtrl">
        <form ng-upload method="post" enctype="multipart/form-data" action="/write" >
            <fieldset>
                <label>Category</label>
                <select name="category_id" class="">
                    <option value="0">Select A Category</option>
                    <?php foreach($categories as $category): ?>
                        <option value="<?= $category -> category_id; ?>"><?= $category -> category_name; ?></option>
                    <?php endforeach; ?>
                </select>

                <label>Title</label>
                <input type="text" class="title span5" name="post_title"
                       placeholder="A catchy title here..."
                       value="<?= $post -> post_title; ?>" />

                <label>Attach Image</label>
                <input type="file" name="post_image" />

                 <a href='javascript:void(0)'  class="upload-submit: uploadPostImage(contents, completed)" >Crop Image</a>

                <label>Body</label>
                <div id="container">
                <textarea id="mytextarea" wrap="off" name="post_content" class="span7" placeholder="Content..."><?= $post -> post_content; ?></textarea> …
Run Code Online (Sandbox Code Playgroud)

javascript angularjs angularjs-http angularjs-fileupload

32
推荐指数
2
解决办法
12万
查看次数

SyntaxError:Object.parse(native)AngularJS上的意外标记o

来自AngularJS noob的问题.

我正在尝试使用asmx Web服务来显示网格.我测试了Web服务,它正确输出了JSON数据.这是我的控制器

app.controller('SetupController', ['$scope', '$http', function ($scope, $http) {

    var url = 'app/pricefilessetup/grid.asmx/getGridJson';

    $http.get(url).success(function (data) {
        var myjson = JSON.parse(data);
        $scope.products= JSON.parse(myjson);
    });
}]);
Run Code Online (Sandbox Code Playgroud)

出于某种原因,SO不允许我粘贴html,但它基本上有一个ng-controller指令和ng-repeat来循环遍历JSON数据.

当我运行这个Web应用程序时,我收到错误

SyntaxError:Object.parse(native)上的意外标记o,它指向以下行

  $scope.questions = JSON.parse(myjson);
Run Code Online (Sandbox Code Playgroud)

我尝试使用alert检查myjson的值,它显示[object Object],[object Object],...

这里有什么我想念的吗?

javascript json angularjs angularjs-http

31
推荐指数
3
解决办法
6万
查看次数

angularJS中$ http.get出错 - 成功不是函数

得到此错误:

angular.min.js:122 TypeError:$ http.get(...).成功不是getUserInfo(app.js:7)中的函数,在new(app.js:12)处于Object.invoke(angular.min) .js:43)在Q.instance(angular.min.js:93)at p(angular.min.js:68)at g(angular.min.js:60)at g(angular.min.js:61) )在angular(min.min.js:61)处于angular.min.js:60 at angular.min.js:21

这是我的代码:

var gitHub = angular.module('gitHub', []);

gitHub.controller('mainController', ['$scope', '$http', function($scope, $http) {

    var $scope.user = '';
    function getUserInfo($scope, $http){ 
        $http.get('https://api.github.com/users')
            .success(function (result) {
                $scope.user = result;
                console.log(result);
            });
    };
    getUserInfo($scope, $http);
}]);
Run Code Online (Sandbox Code Playgroud)

这是html

<!DOCTYPE html>
<html ng-app="gitHub">
<head>
    <title>Github Users Directory</title>
    <script src="angular.min.js"></script>
    <script src="app.js"></script>
</head>
<body>
    <div ng-controller="mainController">
        <div>
            <h1>GitHub Users</h1>
            Who do you want to search for?<input type="text" name="FindHim" ng-model="queryName" />
            <button ng-click="getUserInfo()">Search</button>
        </div>
        <div>
            {{ user …
Run Code Online (Sandbox Code Playgroud)

angularjs angularjs-http angularjs-1.6

26
推荐指数
2
解决办法
5万
查看次数

我们如何测试非范围角度控制器方法?

我们在Angular Controller中有很少的方法,它们不在范围变量上.

有谁知道,我们如何在Jasmine测试中执行或调用这些方法?

这是主要代码.

var testController = TestModule.controller('testController', function($scope, testService)
{

function handleSuccessOfAPI(data) {
    if (angular.isObject(data))
    {
       $scope.testData = data;
    }
}

function handleFailureOfAPI(status) {
    console.log("handleFailureOfAPIexecuted :: status :: "+status);
}

 // this is controller initialize function.
 function init() {
    $scope.testData = null; 

    // partial URL
    $scope.strPartialTestURL = "partials/testView.html;

    // send test http request 
    testService.getTestDataFromServer('testURI', handleSuccessOfAPI, handleFailureOfAPI);
}

 init();
}
Run Code Online (Sandbox Code Playgroud)

现在在我的茉莉花测试中,我们传递"handleSuccessOfAPI"和"handleFailureOfAPI"方法,但这些都是未定义的.

这是茉莉花测试代码.

describe('Unit Test :: Test Controller', function() {
var scope;
var testController;

var httpBackend;
var testService;


beforeEach( function() { …
Run Code Online (Sandbox Code Playgroud)

jasmine angularjs karma-runner angularjs-controller angularjs-http

19
推荐指数
2
解决办法
1万
查看次数