简体   繁体   中英

AngularJS REST API problems

I'm trying to recive data from REST API using POST. I created controller that should make POST request.

function LoginCtrl($scope, $http, $rootScope) {
$scope.login = function () {
    var form = {};
    form.user = $scope.name;
    form.pwd = $scope.password;
    $http({
        method: 'POST',
        url: serverUrl+'/login',
        data: $.param(form),
        headers: {
            'Content-type': 'application/json'
        }
    })
    .success(function(data, status, headers, config) {
        //success
    })
    .error(function(data, status, headers, config) {
        //error
    });
}

When I run this code, browser creates OPTIONS request and show Access-Control-Allow-Origin (see below). My API only work with POST requests and require Content-type header set to application/json.

But when I change Content-type to application/x-www-form-urlencoded browser make POST request, but still I see error:

XMLHttpRequest cannot load http://nimoz.asi.pl:8080/api/login. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. 

How to set Content-type header to application/json, keep POST method and avoid Access-Control-Allow-Origin error?

I use AngularJS version 1.2.10.

EDIT: When I test API on DEV HTTP CLIENT (Chrome extension), request work: http://scr.hu/277/hfwby

This is not a problem with angular, this is a problem with your server. Your browser will not send a request to a server that is on a different domain or port or protocol than the page you're making the request from.

The OPTIONS request and the headers it passes like the Access-Control-Allow-Origin header are part of the CORS protocol. You should research how to implement CORS in your server API. Most web servers contain plugins or the equivalent to automatically allow CORS.

See Wikipedia here for some background on CORS: http://en.wikipedia.org/wiki/Cross-origin_resource_sharing

It's CORS restriction. If ypu have an access to server add header to required page: Access-Control-Allow-Origin: *

If not use JSONP . Here is Angular Docs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM