我试图在单击按钮时发送Ajax请求,但是我似乎无法让控制器返回响应。响应为空;可能是什么问题?
查看
services
.AddAuthentication(auth =>
{
auth.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
auth.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.RequireHttpsMetadata = true;
options.SaveToken = true;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
ValidateIssuer = false,
ValidateAudience = false,
ValidateLifetime = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
RequireExpirationTime = true,
ClockSkew = TimeSpan.Zero
};
options.Events = new JwtBearerEvents
{
OnAuthenticationFailed = ctx =>
{
if (ctx.Exception.GetType() == typeof(SecurityTokenExpiredException))
{
ctx.Response.Headers.Add("Token-Expired", "true");
}
return Task.CompletedTask;
},
OnMessageReceived = ctx =>
{
ctx.Request.EnableBuffering();
using (var reader = new StreamReader(ctx.Request.Body, Encoding.UTF8, true, 1024, true))
{
var jsonBody = reader.ReadToEnd();
var body = JsonConvert.DeserializeObject<BaseRequest>(jsonBody);
ctx.Request.Body.Position = 0;
if (body != null)
{
ctx.Token = body.Token;
}
}
return Task.CompletedTask;
}
};
});
<a href="#" onclick="addtoCart(1, 'test', 2, 8900)"
class="btn essence-btn">Add to Cart</a>
<div hidden id="url" data-url="{{ url('/cart/add') }}"></div>
路线
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
function addtoCart(id, name, quantity, price) {
request = $.ajax({
url: "/cart/add",
method: 'POST',
data:
{
id: id,
name: name,
quantity: quantity,
price: price
},
success: function (data) {
console.log(data);
},
error: function (data) {
console.log('Error:', data);
}
});
}
控制器
Route::group(['prefix' => 'cart'], function () {
Route::post('/add', 'CartController@add');
});
答案 0 :(得分:2)
按如下所示修改您的代码。我认为这会对您有所帮助。
这是路线
Route::group(['prefix' => 'cart'], function (){
Route::post('/add', 'CartController@add')->name('add-cart');
});
这是脚本
function addtoCart(id, name, quantity, price) {
$.post('{{ route('add-cart') }}', {id:id, name:name, quantity:quantity, price:price},
function (data) {
console.log(data);
}
}