[英]Ajax Issues making a post request for my join table full
To the point: 422 error making a post request for my join table using ajax on the front end. 要点:422在前端使用ajax向我的联接表发出发布请求时出错。
I'm creating an app for a fullstack project using rails (as my api) and ajax to make my api request to my routes. 我正在使用rails(作为我的api)和ajax为全栈项目创建一个应用,以向路线发送我的api请求。 I have three tables on my back end (users: :email, :token, :password_digest),(fantasy_players: :player_id, :user_id, :target), and (players: :name, :team, :bye)
我在后端有三个表(用户::email,:token,:password_digest),(幻想玩家::player_id,:user_id,:target)和(玩家::name,:team,:bye)
On my front end i can make a successful post to my players table and my curl requests to my back end seem to work fine for my fantasy_players table. 在我的前端,我可以在我的玩家表上发布成功的帖子,而对后端的卷曲请求对于我的fantasy_players表似乎很好。 I'm receiving a 422 unprocessable entity, the server code reads as follows :
我收到一个422无法处理的实体,服务器代码如下:
Started POST "/fantasy_players" for 127.0.0.1 at 2017-12-02 19:29:38 -0500
Processing by FantasyPlayersController#create as */*
Parameters: {"submit"=>"Add To My Players", "player"=>{"id"=>"1"}, "fantasy_player"=>{"target"=>"yes"}}
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."token" = $1 LIMIT $2 [["token", "92ed3b66f0608a14b0225cad5a362027"], ["LIMIT", 1]]
(0.2ms) BEGIN
(0.2ms) ROLLBACK
[active_model_serializers] Rendered ActiveModel::Serializer::Null with ActiveModel::Errors (0.41ms)
Completed 422 Unprocessable Entity in 8ms (Views: 2.7ms | ActiveRecord: 0.6ms)
const onAddUserPlayer = function (event) {
event.preventDefault()
const data = getFormFields(this)
console.log(data)
api.addUserPlayer(data)
.then(ui.addUserPlayerSuccess)
.catch(ui.addUserPlayerFailure)
}
const addUserPlayer = function (data) {
return $.ajax({
url: config.apiOrigin + '/fantasy_players',
method: 'POST',
headers: {
Authorization: 'Token token=' + store.user.token
},
data
})
}
I think it's CSRF
issue. 我认为这是
CSRF
问题。
The layout which is rendering this corresponding view, should contain this: 呈现此对应视图的布局应包含以下内容:
<%= csrf_meta_tag %>
And it adds CSRF token to your view header, so you can get it easily from frontend using something like: $('meta[name="csrf-token"]').attr('content')
. 并将CSRF令牌添加到您的视图标题中,因此您可以使用类似
$('meta[name="csrf-token"]').attr('content')
类的方法轻松地从前端获得它。
In your case try to add beforeSend
to you ajax
request. 在您的情况下,请尝试将
beforeSend
添加到您的ajax
请求中。 Maybe something like: 也许像:
beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))},
Cheers! 干杯!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.