dongzhuxun5136 2019-02-15 01:29
浏览 69

尝试使用Ember前端访问Golang后端时出现CORS错误

So here is my problem. I am writing a simple application that posts data to an API. Unfortunately I cannot get data to post. Every Time I try to post I get the following error:

Access to XMLHttpRequest at 'http://localhost:8000/api/v1/users' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

(If Anymore Info is Needed To Help Please Just Ask and I will Include It. This Post Was Starting To Get Very Long So I Cut Some Code Out.)

My current code looks like so:

Ember:

route routes/user/add.js

import Route from '@ember/routing/route';

export default Route.extend({
  model: function(){
    return this.store.createRecord('user');
  }
});

Controller /controllers/users/add:

import Controller from '@ember/controller';

export default Controller.extend({
  actions: {
    saveUser: function(){
      this.get('model').save().then(user => this.transitionToRoute('users.user', user));
    }
  }
});

Model models/user

import DS from 'ember-data';

export default DS.Model.extend({
  username: DS.attr('string'),
  password: DS.attr('string'),
  firstName: DS.attr('string'),
  lastName: DS.attr('string'),
  roles: DS.attr('string'),
  pic: DS.attr('string'),
});

View views/users/add

<div class="col-md-12">
  <h4 class='form-label'><b>Add new pet</b></h4>
  <form role="form" id="addUserForm">
    <div class="form-group">
      <label for="username">UserName:</label>
      {{input class="form-control" id="username" value=model.username}}
    </div>
    <div class="form-group">
      <label for="password">password:</label>
      {{input class="form-control" id="password" value=model.password}}
    </div>
    <div class="form-group">
      <label for="firstName">firstName:</label>
      {{input class="form-control" id="firstName" value=model.firstName}}
    </div>

    <div class="form-group">
      <label for="lastName">lastName</label>
      {{input class="form-control" id="lastName" value=model.lastName}}
    </div>

    <div class="form-group">
      <label for="roles">roles</label>
      {{input class="form-control" id="roles" value=model.roles}}
    </div>

    <div class="form-group">
      <label for="pic">pic</label>
      {{input class="form-control" id="pic" value=model.pic}}
    </div>
    <button type="submit" class="btn btn-default" {{action 'saveUser'}}>Submit</button>
  </form>
</div>

GoLang

main.go

import (
    "github.com/rs/cors"
    "log"
    "net/http"
)

func main() {
    r := NewRouter()

    c := cors.New(cors.Options{
        AllowedMethods: []string{"GET","POST", "PATCH", "DELETE", "OPTIONS"},
        AllowedOrigins: []string{"*", "*", "*"},
        AllowCredentials: false,
        AllowedHeaders: []string{"application/json", "Content-Type, Access-Control-Allow-Origin"},
        OptionsPassthrough: true,
        Debug: true,

    })

    handler := c.Handler(r)

    log.Fatal(http.ListenAndServe(":8000", handler))
}

models/user

type User struct {
    Id        int    `jsonapi:"primary,users"`
    Username  string `jsonapi:"attr,username"`
    Password  string `jsonapi:"attr,password"`
    FirstName string `jsonapi:"attr,firstname"`
    LastName  string `jsonapi:"attr,lastname"`
    Role      string `jsonapi:"attr,role"`
    Pic       string `jsonapi:"attr,pic"`
}

apiuserhandler.go

func ModifyUser(w http.ResponseWriter, r *http.Request) {
    fmt.Println("Modify Handler")
    jsonApiRuntime := jsonapi.NewRuntime().Instrument("/")

    vars := mux.Vars(r)
    fmt.Println(vars["id"])

    id, err := strconv.Atoi(vars["id"])

    if err != nil {
        fmt.Println("Invalid User")
        return
    }

    user := ReadUser(&models.User{Id: id})
    if err := jsonApiRuntime.UnmarshalPayload(r.Body, user); err != nil {
        http.Error(w, err.Error(), 500)
        fmt.Println(err.Error())

        return
    }

    UpdateUser(user)

    if err := jsonApiRuntime.MarshalPayload(w, user); err != nil {
        http.Error(w, err.Error(), 500)
    }

    w.WriteHeader(201)
    w.Header().Set("Content-Type", "application/vnd.api+json")
}
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
    • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
    • ¥15 如何在炒股软件中,爬到我想看的日k线
    • ¥15 seatunnel 怎么配置Elasticsearch
    • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
    • ¥15 (标签-MATLAB|关键词-多址)
    • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
    • ¥500 52810做蓝牙接受端
    • ¥15 基于PLC的三轴机械手程序
    • ¥15 多址通信方式的抗噪声性能和系统容量对比