Content-type을 "application/json" POST 메서드, RESTful API로 변경
Angular는 처음입니다.JS와 나는 너의 도움이 필요했다.
API에 json을 POST하고 적절한 답변을 받으면 됩니다.
여기 내 JSON이 있는데 어디에 코드를 붙여야 할지 모르겠어.
JSON
{
"userId" :"testAgent2",
"token" :"testAgent2",
"terminalInfo":"test2",
"forceLogin" :"false"
}
내가 제대로 하고 있는지 모르겠어.
컨트롤러JS
function UserLoginCtrl($scope, UserLoginResource) {
//Save a new userLogin
$scope.loginUser = function() {
var loggedin = false;
var uUsername = $scope.userUsername;
var uPassword = $scope.userPassword;
var uforcelogin = 'true';
UserLoginResource.save();
}
}
서비스JS
angular.module('UserLoginModule', ['ngResource'])
.factory('UserLoginResource', function($resource, $http) {
$http.defaults.useXDomain = true;
delete $http.defaults.headers.common['X-Requested-With'];
$http.defaults.headers.post["Content-Type"] = "application/json"; //NOT WORKING
return $resource('http://123.123.123.123\\:1234/SOME/LOCATION/THERE', {}, {
save: {
method:'POST',
headers: [{'Content-Type': 'application/json'}]
} //NOT WORKING EITHER
});
});
인덱스.HTML
<html ng-app>
<head>
<script src="js/lib/angular/angular.js"></script>
<script src="js/lib/angular/angular-resource.js"></script>
</head>
<body ng-controller="UserLoginCtrl">
<form class="form-horizontal" name="form-horizontal" ng-submit="loginUser();">
<div class="button-login">
<!-- start: button-login -->
<button class="btn btn-primary" type="submit">Login</button>
</div>
</form>
</body>
</html>
Unsupported Media Type(지원되지 않는 미디어 유형)이라는 응답이 계속 왔습니다.또 뭘 해야 할지 모르겠어
최신의 「불안정」릴리즈 중 하나를 사용할 수 있는 경우, 헤더를 변경하는 올바른 구문은 다음과 같습니다.
app.factory('BarService', function ($resource) {
var BarService = $resource('/foo/api/bars/:id', {}, {
'delete': {
method: 'DELETE',
headers: {
'Content-Type': 'application/json'
}
}
});
return BarService;
});
$resource 서비스는 애플리케이션 구축에 매우 효과적인 도구이며 $http까지 줄일 필요가 없을 정도로 성숙되어 있습니다.게다가 패턴과 같은 활동적인 기록은 매우 편리하다.
Angular에서는 JSON 개체를 게시하는 것이 매우 쉽습니다.필요한 것은 다음과 같습니다.
Javascript 개체 만들기
당신의 코드에 있는 당신의 정확한 속성을 사용하겠습니다.
var postObject = new Object();
postObject.userId = "testAgent2";
postObject.token = "testAgent2";
postObject.terminalInfo = "test2";
postObject.forceLogin = "false";
개체를 API에 게시합니다.
API에 개체를 게시하려면 간단한 $http만 있으면 됩니다.포스트 기능아래를 참조해 주세요.
$http.post("/path/to/api/", postObject).success(function(data){
//Callback function here.
//"data" is the response from the server.
});
API에 게시하는 기본 방식은 JSON이므로 리셋할 필요가 없습니다.자세한 내용은 $http 바로가기 링크를 참조하십시오.
특히 코드와 관련하여, 이 간단한 포스트 방식을 포함하도록 저장 방법을 변경해 보십시오.
'Content-Type'을 올바르게 설정하는 방법: 'application/json'은 저장 작업에 transformRequest 함수를 설정하는 것입니다.
angular.module('NoteWrangler')
.factory('NoteNgResource', function NoteNgResourceFactory($resource) {
// https://docs.angularjs.org/api/ngResource/service/$resource
return $resource("./php/notes/:id", {}, {
save : { // redefine save action defaults
method : 'POST',
url : "./php/notes", // I dont want the id in the url
transformRequest: function(data, headers){
console.log(headers);
headers = angular.extend({}, headers, {'Content-Type': 'application/json'});
console.log(headers);
console.log(data);
console.log(angular.toJson(data));
return angular.toJson(data); // this will go in the body request
}
}
});
});
쿼리 매개 변수를 지울 방법이 없는 것 같습니다. 요청에는 둘 다...
언급URL : https://stackoverflow.com/questions/17211443/change-content-type-to-application-json-post-method-restful-api
'programing' 카테고리의 다른 글
JObject를 통해 어떻게 계산합니까? (0) | 2023.03.22 |
---|---|
Twitter API 오류 215 (0) | 2023.03.22 |
React.js: 튜토리얼의 예가 작동하지 않습니다. (0) | 2023.03.17 |
AngularJS : 1개의 Angular 방향에서 여러 서브 요소를 변환합니다. (0) | 2023.03.17 |
WordPress가 빈 post_in 배열에서 쿼리 결과를 표시하는 이유는 무엇입니까? (0) | 2023.03.17 |