@inject HttpClient Http
@page "/"
<button class="checkout" @onclick="() => createOrder()">Place Order</button>
@code {
public List<CartToSendItems> items { get; set; } = new List<CartToSendItems>();
public class CartToSend
{
public Guid customerId { get; set; }
public List<CartToSendItems> items = new List<CartToSendItems>();
}
public class CartToSendItems
{
public int productId { get; set; }
public int qty { get; set; }
}
public async Task createOrder()
{
CartToSend body = new CartToSend();
body.customerId = Guid.Parse("68e03745-e4a2-480f-9f39-eac36aa1ddcd");
body.items = GetItems();
var jsonBody = System.Text.Json.JsonSerializer.Serialize<CartToSend>(body);
Console.WriteLine(jsonBody.ToString());
Console.WriteLine("items: " + body.items.Count.ToString());
var httpResponse = await Http.PostAsJsonAsync<CartToSend>("http://localhost:1337/orders/create", body);
}
protected List<CartToSendItems> GetItems() {
List<CartToSendItems> ret = new List<CartToSendItems>();
CartToSendItems item1 = new CartToSendItems();
item1.productId = 1;
item1.qty = 2;
CartToSendItems item2 = new CartToSendItems();
item2.productId = 4;
item2.qty = 2;
ret.Add(item1);
ret.Add(item2);
return ret;
}
}
This is actually just sending the customerId and the items is being ignored. So the backend server is just receiving: { customerId: '68e03745-e4a2-480f-9f39-eac36aa1ddcd' }
What is the correct way to perform this action ? thanks in advance
EDIT: Example edited for a better understanding as raw.
My consoles outputs:
{"customerId":"68e03745-e4a2-480f-9f39-eac36aa1ddcd"}
items: 2
NodeJS Backend log:
Debugger listening on ws://127.0.0.1:5858/1c18c737-e806-4770-ac13-8bd6e6c821b3
For help, see: https://nodejs.org/en/docs/inspector
Debugger attached.
GET / 304 466.248 ms - -
GET /stylesheets/main.css 304 1.439 ms - -
OPTIONS /orders/create 204 0.463 ms - 0
Missing Fields { customerId: '68e03745-e4a2-480f-9f39-eac36aa1ddcd' }
POST /orders/create 403 18.247 ms - 18
replace this method :
public class CartToSend
{
public Guid customerId { get; set; }
public List<CartToSendItems> items = new List<CartToSendItems>();
}
by :
public class CartToSend
{
public Guid customerId { get; set; }
public List<CartToSendItems> items { get; set; } = new List<CartToSendItems>();
}
'items' was delclared as field that why it does not get serialized