【问题标题】:Laravel API: Get 500 (Internal Server Error) while trying to store datas using JQuery AjaxLaravel API:尝试使用 JQuery Ajax 存储数据时出现 500(内部服务器错误)
【发布时间】:2022-01-12 15:30:49
【问题描述】:

我正在尝试使用 AJAX jQuery 将数据从前端发送到我的 Laravel API,但出现 http 500 错误。

当我使用 Postman 进行测试时,一切正常,但是当我从浏览器进行测试时,我的服务器返回错误。

这是负责发送数据的 JavaScript 代码:

$("#saver").on("click", event => {
   $.ajax({
      data: Tasks,
      type: 'POST', // on précise la methode
      url: url_store, //l'url vers laquelle AJAX doit diriger la requette
     // async:false,
      // on success 
      success: function(response) { // si tout se passe bien NOTE: reponse contient la réponse obtenu de la requette
            console.log(response)
        },
      // on error
      error: function(response) { //sinon
          console.log("the error returned: %o", response)
      }
});

注意:“Task”变量是一个对象表。

这里是负责存储数据的方法:

public function store(Request $request)
{
    //
    $i=0; $data = [];
    if(count($request->all()) != 0 ) {
        foreach ($request->all() as $task) {
            if(TaskSave::create($task)) {
                $i++;
            }
        }

        if($i == count($request->all())) {
            $data = [
                'success' => "Toutes les taches ont été sauvée"
            ];
        } else {
            $data = [
                'error' => "certaines données n'ont pas été sauvées"
            ];
        }
    } else {
        $data = [
            'error' => "Vous n'avez pas envoyé de données"
        ];
    }

    return response()->json( $data, 200);
}

这是回报:

对此的任何提示将不胜感激!

【问题讨论】:

  • 您是否仔细检查过浏览器实际发送的内容并与 Postman 请求进行比较?
  • 你好 @phuzi,是的,我复制了 Tasks 变量的内容,并使用 Postman 将其提交给 API,一切正常
  • 好的,但是您检查浏览器发送的内容是否与 Postman 发送的内容相同?检查开发工具和邮递员控制台中的浏览器网络面板
  • 我看到在我的浏览器中,“content-Type”标头的值为“text / html; charset = UTF-8”,这是一个问题吗?因为在 Postman 中它被设置为“applicaytion/json”,如果是,我该如何在 Ajax 中设置 content-Type?
  • 这可能是 csrf-token 的问题吗?因为我没有使用表单来发布我的数据,它只是我创建的对象的集合

标签: jquery ajax api post laravel-8


【解决方案1】:

终于找到了适合我的解决方案:

$("#saver").on("click", event => {
    console.log( JSON.stringify(Tasks))
    $.ajax({
        type: 'POST', // on précise la methode
        url: url_store, //l'url vers laquelle AJAX doit diriger la requette
        data: JSON.stringify(Tasks),
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        // async:false,
        // on success 
        success: function(response) { // si tout se passe bien NOTE: reponse contient la réponse obtenu de la requette
                alert(response.success)
            },
        // on error
        error: function(response) { //sinon
            console.log("the error returned: %o", response)
        }
    });
})

显然,要考虑到,必须将数据更改为字符串。 然后我还将 contentType 更改为“application/json; charset=utf-8”。 此解决方案对我有用,希望对其他人有所帮助。

【讨论】:

    猜你喜欢
    • 2012-01-08
    • 2020-02-06
    • 2012-07-11
    • 2020-10-07
    • 1970-01-01
    • 2021-01-12
    • 1970-01-01
    • 2016-11-26
    • 1970-01-01
    相关资源
    最近更新 更多