我以某种方式收到 HTTP 422 响应: 状态码:422 不可处理的实体
fmt.Println(c) 的控制台消息是:
&{{0xc04227c1c0 -1 200} 0xc0421b2100 0xc042086d10 [] [0x8fdc00 0x8fe950 0x97e310 0x97cf80] 3 0xc0421ea5a0 map[] []}
map 应该填写 myEmail 和 myPassword 但事实并非如此。
body有问题还是和web API有关?
这是我的 HTTP 请求:
this.http.post('http://localhost:8080/api/v1/users', {'email': 'myEmail', 'password': 'myPassword'}, httpOptions)
.subscribe(data => {
console.log('register___', data);
});
这是 httpOptions:
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json'
, 'Access-Control-Allow-Origin': '*'
, 'Access-Control-Allow-Headers': 'access-control-allow-origin, access-control-allow-headers'})
};
这是我正在使用的 go web API:
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"github.com/jinzhu/gorm"
_ "github.com/mattn/go-sqlite3"
)
type Users struct {
email string `gorm:"not null" form:"email" json:"email"`
password string `gorm:"not null" form:"password" json:"password"`
}
func InitDb() *gorm.DB {
// Openning file
db, err := gorm.Open("sqlite3", "./data.db")
// Display SQL queries
db.LogMode(true)
// Error
if err != nil {
panic(err)
}
// Creating the table
if !db.HasTable(&Users{}) {
db.CreateTable(&Users{})
db.Set("gorm:table_options", "ENGINE=InnoDB").CreateTable(&Users{})
}
return db
}
func Cors() gin.HandlerFunc {
return func(c *gin.Context) {
c.Writer.Header().Add("Access-Control-Allow-Origin", "http://localhost:4200")
c.Next()
}
}
func main() {
r := gin.Default()
r.Use(Cors())
v1 := r.Group("api/v1")
{
v1.POST("/users", PostUser)
v1.OPTIONS("/users", OptionsUser)
v1.GET("/users", GetUsers)
v1.GET("/users/:id", GetUser)
v1.PUT("/users/:id", UpdateUser)
v1.DELETE("/users/:id", DeleteUser)
}
r.Run(":8080")
}
func PostUser(c *gin.Context) {
fmt.Println("___herewego___")
db := InitDb()
defer db.Close()
var user Users
c.Bind(&user)
fmt.Println(c)
fmt.Println("_____")
fmt.Println(user)
if user.email != "" && user.password != "" {
fmt.Println("geldim gördüm gidiyorum.....................")
// INSERT INTO "users" (name) VALUES (user.Name);
db.Create(&user)
// Display error
c.JSON(201, gin.H{"success": user})
} else {
// Display error
c.JSON(422, gin.H{"error": "Fields are empty"})
}
// curl -i -X POST -H "Content-Type: application/json" -d "{ \"email\": \"Thea\", \"password\": \"Queen\" }" http://localhost:8080/api/v1/users
}
func GetUsers(c *gin.Context) {
// Connection to the database
db := InitDb()
// Close connection database
defer db.Close()
var users []Users
// SELECT * FROM users
db.Find(&users)
// Display JSON result
c.JSON(200, users)
// curl -i http://localhost:8080/api/v1/users
}
func GetUser(c *gin.Context) {
// Connection to the database
db := InitDb()
// Close connection database
defer db.Close()
email := c.Params.ByName("email")
var user Users
// SELECT * FROM users WHERE id = 1;
db.First(&user, email)
if user.email != "" {
// Display JSON result
c.JSON(200, user)
} else {
// Display JSON error
c.JSON(404, gin.H{"error": "User not found"})
}
// curl -i http://localhost:8080/api/v1/users/1
}
func UpdateUser(c *gin.Context) {
// Connection to the database
db := InitDb()
// Close connection database
defer db.Close()
// Get id user
email := c.Params.ByName("email")
var user Users
// SELECT * FROM users WHERE id = 1;
db.First(&user, email)
if user.email != "" && user.password != "" {
if user.email != "" {
var newUser Users
c.Bind(&newUser)
result := Users{
email: newUser.email,
password: newUser.password,
}
// UPDATE users SET email='newUser.email', password='newUser.password' WHERE id = user.Id;
db.Save(&result)
// Display modified data in JSON message "success"
c.JSON(200, gin.H{"success": result})
} else {
// Display JSON error
c.JSON(404, gin.H{"error": "User not found"})
}
} else {
// Display JSON error
c.JSON(422, gin.H{"error": "Fields are empty"})
}
// curl -i -X PUT -H "Content-Type: application/json" -d "{ \"email\": \"Thea\", \"password\": \"Merlyn\" }" http://localhost:8080/api/v1/users/1
}
func DeleteUser(c *gin.Context) {
// Connection to the database
db := InitDb()
// Close connection database
defer db.Close()
// Get id user
email := c.Params.ByName("email")
var user Users
// SELECT * FROM users WHERE id = 1;
db.First(&user, email)
if user.email != "" {
// DELETE FROM users WHERE id = user.Id
db.Delete(&user)
// Display JSON result
c.JSON(200, gin.H{"success": "User #" + email + " deleted"})
} else {
// Display JSON error
c.JSON(404, gin.H{"error": "User not found"})
}
// curl -i -X DELETE http://localhost:8080/api/v1/users/1
}
func OptionsUser(c *gin.Context) {
c.Writer.Header().Set("Access-Control-Allow-Methods", "DELETE,POST, PUT")
c.Writer.Header().Set("Access-Control-Allow-Headers", "access-control-allow-headers,access-control-allow-origin,content-type")
c.Next()
}
最佳答案
您需要导出数据结构中的字段:
type Users struct {
Email string `gorm:"not null" form:"email" json:"email"`
Password string `gorm:"not null" form:"password" json:"password"`
}
它们当前未导出,因此仅对您的包裹可见。这意味着编码/解码您的数据结构的包将无法看到这些字段。
关于angular - 从 Angular 到 GO 的 HTTP 请求 => 状态代码 :422 Unprocessable Entity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48033176/
我需要在客户计算机上运行Ruby应用程序。通常需要几天才能完成(复制大备份文件)。问题是如果启用sleep,它会中断应用程序。否则,计算机将持续运行数周,直到我下次访问为止。有什么方法可以防止执行期间休眠并让Windows在执行后休眠吗?欢迎任何疯狂的想法;-) 最佳答案 Here建议使用SetThreadExecutionStateWinAPI函数,使应用程序能够通知系统它正在使用中,从而防止系统在应用程序运行时进入休眠状态或关闭显示。像这样的东西:require'Win32API'ES_AWAYMODE_REQUIRED=0x0
如何在buildr项目中使用Ruby?我在很多不同的项目中使用过Ruby、JRuby、Java和Clojure。我目前正在使用我的标准Ruby开发一个模拟应用程序,我想尝试使用Clojure后端(我确实喜欢功能代码)以及JRubygui和测试套件。我还可以看到在未来的不同项目中使用Scala作为后端。我想我要为我的项目尝试一下buildr(http://buildr.apache.org/),但我注意到buildr似乎没有设置为在项目中使用JRuby代码本身!这看起来有点傻,因为该工具旨在统一通用的JVM语言并且是在ruby中构建的。除了将输出的jar包含在一个独特的、仅限ruby
在rails源中:https://github.com/rails/rails/blob/master/activesupport/lib/active_support/lazy_load_hooks.rb可以看到以下内容@load_hooks=Hash.new{|h,k|h[k]=[]}在IRB中,它只是初始化一个空哈希。和做有什么区别@load_hooks=Hash.new 最佳答案 查看rubydocumentationforHashnew→new_hashclicktotogglesourcenew(obj)→new_has
我有一个对象has_many应呈现为xml的子对象。这不是问题。我的问题是我创建了一个Hash包含此数据,就像解析器需要它一样。但是rails自动将整个文件包含在.........我需要摆脱type="array"和我该如何处理?我没有在文档中找到任何内容。 最佳答案 我遇到了同样的问题;这是我的XML:我在用这个:entries.to_xml将散列数据转换为XML,但这会将条目的数据包装到中所以我修改了:entries.to_xml(root:"Contacts")但这仍然将转换后的XML包装在“联系人”中,将我的XML代码修改为
是的,我知道最好使用webmock,但我想知道如何在RSpec中模拟此方法:defmethod_to_testurl=URI.parseurireq=Net::HTTP::Post.newurl.pathres=Net::HTTP.start(url.host,url.port)do|http|http.requestreq,foo:1endresend这是RSpec:let(:uri){'http://example.com'}specify'HTTPcall'dohttp=mock:httpNet::HTTP.stub!(:start).and_yieldhttphttp.shou
在我的Controller中,我通过以下方式在我的index方法中支持HTML和JSON:respond_todo|format|format.htmlformat.json{renderjson:@user}end在浏览器中拉起它时,它会自然地以HTML呈现。但是,当我对/user资源进行内容类型为application/json的curl调用时(因为它是索引方法),我仍然将HTML作为响应。如何获取JSON作为响应?我还需要说明什么? 最佳答案 您应该将.json附加到请求的url,提供的格式在routes.rb的路径中定义。这
关闭。这个问题需要detailsorclarity.它目前不接受答案。想改进这个问题吗?通过editingthispost添加细节并澄清问题.关闭8年前。Improvethisquestion在首页我有:汽车:VolvoSaabMercedesAudistatic_pages_spec.rb中的测试代码:it"shouldhavetherightselect"dovisithome_pathit{shouldhave_select('cars',:options=>['volvo','saab','mercedes','audi'])}end响应是rspec./spec/request
当我的预订模型通过rake任务在状态机上转换时,我试图找出如何跳过对ActiveRecord对象的特定实例的验证。我想在reservation.close时跳过所有验证!叫做。希望调用reservation.close!(:validate=>false)之类的东西。仅供引用,我们正在使用https://github.com/pluginaweek/state_machine用于状态机。这是我的预订模型的示例。classReservation["requested","negotiating","approved"])}state_machine:initial=>'requested
我的主要目标是能够完全理解我正在使用的库/gem。我尝试在Github上从头到尾阅读源代码,但这真的很难。我认为更有趣、更温和的踏脚石就是在使用时阅读每个库/gem方法的源代码。例如,我想知道RubyonRails中的redirect_to方法是如何工作的:如何查找redirect_to方法的源代码?我知道在pry中我可以执行类似show-methodmethod的操作,但我如何才能对Rails框架中的方法执行此操作?您对我如何更好地理解Gem及其API有什么建议吗?仅仅阅读源代码似乎真的很难,尤其是对于框架。谢谢! 最佳答案 Ru
我的假设是moduleAmoduleBendend和moduleA::Bend是一样的。我能够从thisblog找到解决方案,thisSOthread和andthisSOthread.为什么以及什么时候应该更喜欢紧凑语法A::B而不是另一个,因为它显然有一个缺点?我有一种直觉,它可能与性能有关,因为在更多命名空间中查找常量需要更多计算。但是我无法通过对普通类进行基准测试来验证这一点。 最佳答案 这两种写作方法经常被混淆。首先要说的是,据我所知,没有可衡量的性能差异。(在下面的书面示例中不断查找)最明显的区别,可能也是最著名的,是你的