AngularJS and Go POST Request Method Not Allowed - javascript

Im currently working on a sample project and Im using Go and AngularJS I am new at this. I encountered a 405 Error Method Not Allowed after executing this codes.
sample.js
var app = angular.module('sample', []);
app.controller('sampleCtrl', function($scope, $http){
$scope.submit = function(){
//variables
$scope.firstName = document.getElementById('firstName').value;
$scope.middleName = document.getElementById('middleName').value;
$scope.lastName = document.getElementById('lastName').value;
$scope.age = document.getElementById('age').value;
$http({
method: 'POST',
url: baseUrl +'/sample',
headers: {'Content-Type': 'application/json'},
data: {
"firstName" : $scope.firstName,
"middleName" : $scope.middleName,
"lastName" : $scope.lastName,
"age" : $scope.age
}
}).then(function successCallback(response){
alert('Success');
});
}
});
sample.go
package controllers
import (
"github.com/astaxie/beego"
"net/http"
"fmt"
"encoding/json"
)
type SampleController struct {
beego.Controller
}
func (this *SampleController) Get(){
this.TplName = "sample/sample.html"
this.Render()
}
type Entry struct {
FirstName string
MiddleName string
LastName string
Age int
}
func (this *SampleController) Submit(rw http.ResponseWriter, req *http.Request){
decoder := json.NewDecoder(req.Body)
var data Entry
err := decoder.Decode(&data)
if err != nil {
fmt.Println("JSON Empty")
}else{
var firstName = data.FirstName
//var middle = data.MiddleName
//var lastName = data.LastName
//var age = data.Age
fmt.Println(firstName)
}
}
routers.go
package routers
import (
"test/controllers"
"github.com/astaxie/beego"
)
func init() {
beego.Router("/", &controllers.MainController{})
beego.Router("/sample", &controllers.SampleController{}) beego.Router("/sample/Submit",&controllers.SampleController{},"post:Submit")
}
Thanks for the help in advance.

Remove baseUrl and make sure url:"sample".
Maybe you can do this
console.log(baseUrl);
Check that baseUrl contains #;

I am not a Go developer, but looking at the error code it seems like you are making POST request, but have only defined routes for GET.

In router u have defined "/sample" as GET but you made an ajax call for POST method, its search's in the router for /sample it will find this
beego.Router("/sample", &controllers.SampleController{})
which redirects to SampleController but there it doesn't find any POST method definition so 405 method not found.
Try adding in samplecontroller
func (this *SampleController) Post(){
...// your code goes here
}
or add
beego.Router("/sample", &controllers.SampleController{"post:Sample"})
and add a Function Sample in samplecontroller just as you did for Submit

Related

Angular js Web Application failed to Return Expected Message

I am consuming WCF Rest Service into Angular js web application. First I am checking username in database . If the username name is exist then i want to display message in angular js web application is username name is exist please choose other username .If username is not exist then i want to insert the record into database .But the problem is its not displaying message username is not displaying expected message and i got following error .
The server encountered an error processing the request. The exception message is 'Non-static method requires a target.'. See server logs for more details. The exception stack trace is:
Here is the Method.
public bool RegisterUserEncryptPassword(tblUser user)
{
using (HalifaxDatabaseEntities context = new HalifaxDatabaseEntities())
{
var query = (from x in context.tblUsers
where x.Username == user.Username
select x).SingleOrDefault();
if (query != null)
{
return true;
}
else
{
tblUser createUser = new tblUser();
createUser.Username = user.Username;
createUser.Password = Utility.Encrypt(user.Password);
createUser.Email = user.Email;
ctx.tblUsers.Add(createUser);
ctx.SaveChanges();
}
}
return false;
}
Here is my script code..
var app = angular.module("WebClientModule", [])
.controller('Web_Client_Controller', ["$scope", 'myService', function ($scope, myService) {
$scope.OperType = 1;
$scope.createuser = function () {
var User = {
Username: $scope.Username,
Password: $scope.Password,
Email: $scope.Email
};
if ($scope.OperType === 1) {
var promisePost = myService.post(User);
promisePost.then(function (pl) {
$scope.Id = pl.data.Id;
window.location.href = "/Login/Index";
ClearModels();
}, function (err) {
$scope.msg = "Password Incorrect or username is exit !";**//Always Hit on This line**
console.log("Some error Occured" + err);
});
}
}]);
app.service("myService", function ($http) {
//Create new record
this.post = function (User) {
var request = $http({
method: "post",
url: "http://localhost:52098/HalifaxIISService.svc/RegisterUserEncryptPassword",
data: JSON.stringify(User)
});
return request;
};
})
Here is the Screen shot when i run the application.When i try to insert new record i i want to display
here is error message in network tab.
You need to bind the #scope.msg into an html element like label or span. This html element must be loaded inside the DOM with hidden status. You have to just show it with ng-show.

Angularjs factory inject is not working

I am developing a web application in Angularjs. I am making some API calls using $http service. I am using factories to call $http services. I have below controller.
(function () {
angular.module('RoslpApp').controller('SavedVechilces', ['$scope','DeleteVechicle', function ($scope,DeleteVechicle)
$scope.deletesavedCar = function (sref) {
DeleteVechicle.deleteCar(sref.CarID).success(function (resposne) { console.log(resposne) }.error(function (error) { console.log(error)}))
}
}]);
})();
RoslpApp.factory("DeleteVechicle", ['$http', '$cookieStore','cfg', function ($http, $cookieStore,cfg) {
var factoryObject = {};
var baseurl = cfg.Baseurl;
var LoginID = $cookieStore.get("LoginID");
var cookiePreferredLanguage = $cookieStore.get('PreferredLanguage');
var urlapi = baseurl + "api/Vehicle/DeleteSavedVehicle";
factoryObject.deleteCar = function (carID) {
var request = {
url: urlapi,
method: 'POST',
data: {
LoginID: LoginID,
CarID: carID
},
headers: {
RequestedPlatform: "Web",
RequestedLanguage: cookiePreferredLanguage
},
};
return $http(request);
}
return factoryObject;
}
]);
When I run above code I will get Unknown provider: DeleteVechicleProvider <- DeleteVechicle <- SavedVechilce error. I injected DeleteVechicle in my controller. May I know the way I am CarID to the factory and returning response is the correct way? Any help would be appreciated. Thank you.
There are two issues, you need to change your controller/factory as,
RoslpApp.controller
also the request should be,
DeleteVechicle.deleteCar(sref.CarID).then(function(response){
console.log(resposne)
},function(error){
console.log(error)
});

org.springframework.web.HttpRequestMethodNotSupportedException

Need help with the exception getting whilst posting data to server, although GET method works fine within the same REST Resource. Code is given below; Early attention appreciated.
REST Endpoint
#RestController
#RequestMapping("/trading-api")
public class MemberMessageResource {
private final Logger log = LoggerFactory.getLogger(MemberMessageResource.class);
#Inject
MemberMessageService service;
#RequestMapping(value = "/messages/reply/", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<MemMessage> replyMemeberMessage(#RequestBody MemMessage msg)
throws URISyntaxException {
log.info("REST Request to reply a message : {" + msg.toString() + " }");
MemMessage result = msg;
return new ResponseEntity<MemMessage>(result, HttpStatus.OK);
}
}
MessageService.js
'use strict';
angular.module('nkApp').factory(
'messagesService',
[
'$http',
'$q',
function($http, $q) {
var REST_SERVICE_URI = '/trading-api/messages/';
var factory = {
replyMemeberMessage : replyMemeberMessage
};
return factory;
function replyMemeberMessage(message) {
console.log('Replying Message : ', message);
var deferred = $q.defer();
$http.post(REST_SERVICE_URI + "reply/" + message)
.then(
function (response) {
deferred.resolve(response.data);
},
function(errResponse){
console.error('Error while Replying Message');
deferred.reject(errResponse);
}
);
return deferred.promise;
}
} ]);
Console Error
2017-03-10 23:49:21.515 WARN 11764 --- [nio-8080-exec-8] o.s.web.servlet.PageNotFound : Request method 'POST' not supported
Browser Error
{"timestamp":1489189761519,"status":405,"error":"Method Not Allowed","exception":"org.springframework.web.HttpRequestMethodNotSupportedException","message":"Request method 'POST' not supported","path":"/trading-api/messages/reply/[object%20Object]"}
Your message object should not be part of your url, it should be your request body. Instead of adding to the url string, just pass it as the data argument in your angular javascript function:
$http.post(REST_SERVICE_URI + "reply/", message)

AngularJs form post data giving null values in my spring controller

Hello all i am trying to post a form using angular but i am getting null values in my spring controller.Also in my console i see null values for the sysout.Moreover i get an error alert even though i see bull is printed on my console.
My JS Controller
angular.module('ngMailChimp', ['ngAria', 'ngMessages', 'ngAnimate'])
.controller('SignUpController', function ($scope, $http) {
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded; charset=utf-8";
var ctrl = this,
newCustomer = { firstName:'',lastName:'',email:'',streetName:'',aptName:'',cityName:'',stateName:'',countryName:'', zipName:'', userName:'',password:'' };
var signup = function () {
if( ctrl.signupForm.$valid) {
ctrl.showSubmittedPrompt = true;
var formData = {
'firstName' : $scope.ctrl.newCustomer.firstName,
'lastName' : $scope.ctrl.newCustomer.lastName,
'email' : $scope.ctrl.newCustomer.email,
'streetName' : $scope.ctrl.newCustomer.streetName,
'aptName' : $scope.ctrl.newCustomer.aptName,
'cityName' : $scope.ctrl.newCustomer.cityName,
'stateName' : $scope.ctrl.newCustomer.stateName,
'countryName' : $scope.ctrl.newCustomer.countryName,
'zipName' : $scope.ctrl.newCustomer.zipName,
'userName' : $scope.ctrl.newCustomer.userName,
'password' : $scope.ctrl.newCustomer.password
};
var response = $http.post('http://localhost:8080/Weber/user/save', JSON.stringify(formData));
response.success(function(data, status, headers, config) {
$scope.list.push(data);
});
response.error(function(data, status, headers, config) {
alert( "Exception details: " + JSON.stringify({data: data}));
});
}
};
My Spring controller
#RestController
#RequestMapping(value = "/user")
public class UserRegistrationControllerImpl implements UserRegistrationController {
#Autowired
UserRegistrationDao userDao;
#RequestMapping(value = "/save", method = RequestMethod.POST)
public String saveUser(UserRegistration userReg) {
System.out.println(userReg.getFirstName()+" "+userReg.getLastName());
userDao.registerUser(userReg);
return "success";
}
Please help me out
Thank you
mark.
There is no mapper specified for converting JSON to Java object.
Use Jackson(dore, databind, annotations) if you want the JSON to be converted to object of UserRegistration.
Check this out: Convert nested java objects to Jackson JSON
Need to add below in dispatcher-servlet. This is for mapping the JSON to Java objects:
<beans:bean
class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<beans:property name="messageConverters">
<beans:list>
<beans:ref bean="jsonMessageConverter" />
</beans:list>
</beans:property>
</beans:bean>
<!-- Configure bean to convert JSON to POJO and vice versa -->
<beans:bean id="jsonMessageConverter"
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
</beans:bean>
EDIT 1:
Is the method in controller something like this?
#RequestMapping(value = "/save", method = RequestMethod.POST, headers = "Accept=application/json")
public String saveUser(#RequestBody UserRegistration userReg) {
System.out.println(userReg.getFirstName()+" "+userReg.getLastName());
userDao.registerUser(userReg);
return "success";
}
Use above if you are not responding back to the webpage with a result to be consumed. If you want something to be returned from this method and displayed in the webpage or consumed elsewhere, the declaration of method would change to:
public #ResponseBody String saveUser(#RequestBody UserRegistration userReg)
EDIT 2:
$scope.post = function() {
$scope.data = null;
$http({
method : 'POST',
url : 'save',
params : {
firstName : $scope.ctrl.newCustomer.firstName,
lastName : $scope.ctrl.newCustomer.lastName,
email : $scope.ctrl.newCustomer.email,
streetName : $scope.ctrl.newCustomer.streetName,
aptName : $scope.ctrl.newCustomer.aptName,
cityName : $scope.ctrl.newCustomer.cityName,
stateName : $scope.ctrl.newCustomer.stateName,
countryName : $scope.ctrl.newCustomer.countryName,
zipName : $scope.ctrl.newCustomer.zipName,
userName : $scope.ctrl.newCustomer.userName,
password : $scope.ctrl.newCustomer.password
}
}).success(function(data, status, headers, config) {
$scope.list.push(data);
}).error(function(data, status, headers, config) {
alert("Exception");
});
};
Try add #RequestBody in the method arguments:
#RequestMapping(value = "/save", method = RequestMethod.POST)
public String saveUser(#RequestBody UserRegistration userReg) {
System.out.println(userReg.getFirstName()+" "+userReg.getLastName());
userDao.registerUser(userReg);
return "success";
}

How should I extract value from Url in Node Js

I recently started programming on nodeJs.
I am using Angular JS, resource to call API's as
demoApp.factory('class', function ($resource) {
return $resource('/class/:classId', { classId: '#_classId' }, {
update: { method: 'PUT' }
});
});
And in Controller, I have delete method as;
// The class object, e {classId: 1, className: "Pro"}
$scope.deleteClass = function (class) {
var deleteObj = new Class();
deleteObj.classId = class.classId;
deleteObj.$delete({classId : deleteObj.classId}, function() {
growl.success("Class deleted successfully.");
$location.path('/');
},function () {
growl.error("Error while deleting Class.");
}
);
};
Using browser, I verified call goes to :
http://localhost:3000/class/1
Now in node Js, How should I extract value from Url,
In server.js
app.use('/class', classController.getApi);
In classController.js
exports.getApi = function(req, resp){
switch(req.method) {
case 'DELETE':
if (req) {
// how to extract 1 from url.
}
else {
httpMsgs.show404(req, resp);
}
break;
I have tried ,
console.log(req.params);
console.log(req.query);
But no luck.
I am seeing
console.log(req._parsedUrl);
query: null,
pathname: '/class/1',
path: '/class/1',
Any help appreciated.
This should be a get call right ? You can use angular $http service, with method as get. Replace your app.use('/class') with app.get('/class', function). Then you can use req.param('classId') to retrieve data. I think it should work.
Try updating your app.use to app.use('/class/:classId'), then try req.params.classId
Try using req.hostname as in:
`http://host/path'
Check this answer.
Tldr;
var url = require('url');
var url_parts = url.parse(request.url, true);
var query = url_parts.query;
Also read the docs on node url.

Categories

Resources