不允许使用AngularJS和Go POST请求方法

时间:2016-04-05 02:33:52

标签: javascript jquery angularjs go beego

我目前正在研究一个示例项目,我正在使用Go和AngularJS我是新手。执行此代码后,我遇到了405错误方法不允许。

sample.js



if(IdenticalArrays.equals == true)
      {
         System.out.print("The two arrays are identical.");
      }
      else if(IdenticalArrays.equals == false)
      {
         System.out.print("The two arrays are not identaical.");
      }




sample.go

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');
	  });
    }
});

routers.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)
    }
}




感谢您的帮助。

3 个答案:

答案 0 :(得分:0)

删除baseUrl并确保url:"sample"。 也许你可以做到这一点 console.log(baseUrl); 检查baseUrl是否包含#;

答案 1 :(得分:0)

我不是Go开发人员,但查看错误代码似乎是在发出POST请求,但只定义了GET的路由。

答案 2 :(得分:0)

在路由器中你已经定义了" / sample"作为GET但是你为POST方法做了一个ajax调用,它在路由器中搜索/ sample它会发现这个

beego.Router(" / sample",& controllers.SampleController {})

重定向到SampleController,但它没有找到任何POST方法定义,因此找不到405方法。

尝试添加samplecontroller

func(this * SampleController)Post(){    ... //你的代码就在这里 }

或添加

beego.Router(" / sample",& controllers.SampleController {" post:Sample"})

并在samplecontroller中添加一个Function Sample,就像你提交

一样