0

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

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

示例.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)
    }
}

路由器.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")
}

我在这里先向您的帮助表示感谢。

4

3 回答 3

0

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

于 2016-04-15T01:25:16.303 回答
0

我不是 Go 开发人员,但查看错误代码似乎您正在发出POST请求,但只为GET.

于 2016-04-05T04:07:57.417 回答
0

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

于 2016-04-05T03:29:25.270 回答