[英]AngularJS and Go POST Request Method Not Allowed
我目前正在研究一個示例項目,而我正在使用Go和AngularJS。 執行此代碼后,我遇到“ 405錯誤方法不允許”。
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") }
我在這里先向您的幫助表示感謝。
刪除baseUrl並確保url:"sample"
。 也許您可以這樣做console.log(baseUrl);
檢查baseUrl是否包含#
;
我不是Go開發人員,但是看着錯誤代碼,您好像在發出POST
請求,但只為GET
定義了路由。
在路由器中,您已經將“ / sample”定義為GET,但是您對POST方法進行了ajax調用,它在路由器中搜索/ sample會找到它
beego.Router(“ / sample”,&controllers.SampleController {})
它重定向到SampleController,但在那里找不到任何POST方法定義,因此找不到405方法。
嘗試添加samplecontroller
func(此* SampleController)Post(){... //您的代碼在此處}
或添加
beego.Router(“ / sample”,&controllers.SampleController {“ post:Sample”})
並像在Submit中一樣在samplecontroller中添加一個功能樣本
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.