【发布时间】:2022-02-15 17:52:24
【问题描述】:
我目前正在使用 ajax 从我的 Web 应用程序向 api 服务器发送数据。 但是服务器无法读取我的数据,因为我的数据的typeData与邮递员发送的typeData不同。
我正在测试从邮递员发送数据并且工作正常。 这是通过邮递员发送数据的捕获。
这是我的 ajax 代码
data = {
nama_lengkap: "user name",
nama_panggilan: "user",
ttl: "new york, 10 april 1999",
jenis_kelamin: "male",
agama: "-",
email: "username@mailinator.com",
no_telp: "1234567",
nama_ayah: "Johnson",
nama_ibu: "Kadita",
pendidikan_terakhir: "S1",
organisasi: "-",
kejuaraan: "-",
};
obj = JSON.stringify(data);
t = Cookies.get("user");
$.ajaxSetup({
headers: {
"X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
accept: "application/json",
},
});
$.ajax({
type: "POST",
timeout: 0,
headers: {
Accept: "application/json",
},
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "Bearer " + t);
},
url: "http://localhost:8000/api/anggota/store",
contentType: "application/json",
data: obj,
dataType: "json",
processData: false,
contentType: false,
success: function (response) {
console.log(response);
},
error: function (xhr, status, err) {
console.error(JSON.parse(xhr.responseText));
},
});
但我收到了这样的错误响应文本
{
"success": false,
"code": 500,
"message": "Gagal",
"errors": [
{
"nama_lengkap": [
"The nama lengkap field is required."
],
"nama_panggilan": [
"The nama panggilan field is required."
],
"ttl": [
"The ttl field is required."
],
"jenis_kelamin": [
"The jenis kelamin field is required."
],
"agama": [
"The agama field is required."
],
"email": [
"The email field is required."
],
"no_telp": [
"The no telp field is required."
],
"nama_ayah": [
"The nama ayah field is required."
],
"nama_ibu": [
"The nama ibu field is required."
],
"pendidikan_terakhir": [
"The pendidikan terakhir field is required."
]
}
]
}
嗯,我的代码有什么问题?任何线索都有帮助。
谢谢
【问题讨论】:
-
控制台是否出现跨域错误?
-
我的控制台没有跨域错误。
-
在
http://localhost:8000同一个端口运行这段代码? -
是的。我的 api 和 web 在同一个端口上运行。我认为问题不在于那里。因为我成功登录、注销和注册。但数据格式是 FormData 而不是像我上面的代码那样的原始 json。
-
Please don't add SOLVED to the title of your question。如果已通过答案解决,您可以接受该答案,如果您自己解决了问题,请write your own answer 并接受。