{Rails with Fetch} 通过 fetch 请求存储表单数据:错误“SyntaxError:字符串与预期模式不匹配”

问题描述

我已经尝试了三天让 Rails 使用 fetch 将表单数据保存到数据库,但无济于事。在我的研究中,我遇到了 Stimulus JS 和 Stimulus Reflex。这可能是未来需要考虑的事情,但目前我很乐意让它发挥作用。

我正在使用 initSelect2 gem 输入标签。这些必须保存到与输入到其余输入中的数据库不同的数据库中。

点击提交按钮后,我正在准备如下值:

const project = {};
project.vision = document.querySelector('#project_vision').value || null;
...
console.log(project);

然后我运行一个获取请求:

fetch(`../projects/`,{
            method: 'POST',headers: {
              'Content-Type': 'application/json','Accept': 'application/json','X-Transaction': 'Creating new project','X-Requested-With': 'XMLHttpRequest','X-CSRF-Token': document.querySelector("[name='csrf-token']").content
            },body: JSON.stringify({project: project}),credentials: 'include'
          })
          .then(response => {
            if (!response.ok) {
              throw response;
            }
            return response.json();
          })
          .then(data => {
            console.log('Success:',data);
            alert('saved');
          })
          .catch(error => {
            console.error('Error:',error);
            alert('error');
          });
    });

相关控制器执行以下操作:

def create
   @project = Project.create(project_params)
    if @project.valid?
      respond_to do |format|
        format.json { render json: { "message": "success!",status: :ok } }
      end
    end
end

def project_params
    params.require(:project).permit(
      :name,:language,:slogan,:target,:pain,:solution,:originality,:vision,:db_design_url,:repo_url,:proto_url,:topics,:tags
    )
end

在控制台中,我收到以下错误

SyntaxError: The string did not match the expected pattern.

在网络选项卡中,我只得到:

An error occurred trying to load the resource.

这个问题似乎与强参数有关,尽管我不确定我在这里做错了什么。

更新 1

来自服务器日志:

Started POST "/projects/" for ::1 at 2021-01-03 01:14:13 +0100
Processing by ProjectsController#create as JSON
  Parameters: {"project"=>{"name"=>nil,"tags"=>[],"language"=>"Rails","slogan"=>nil,"target"=>nil,"pain"=>nil,"solution"=>nil,"originality"=>nil,"vision"=>nil,"db_design_url"=>nil,"repo_url"=>nil,"proto_url"=>nil}}
  User Load (0.6ms)  SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2  [["id",1],["LIMIT",1]]
Unpermitted parameter: :tags
No template found for ProjectsController#create,rendering head :no_content
Completed 204 No Content in 13ms (ActiveRecord: 0.6ms | Allocations: 3948)
# Project model
class Project < ApplicationRecord
  has_many :Feedbacks
  has_many :teams
  has_many :likes
  has_many :issues
  has_many :project_features
  has_many :project_stages
  has_many :project_tags
  has_many :tags,through: :project_tags

  validates :name,presence: true
end

在图形上,简化的部分架构如下所示:i.stack.imgur.com/rTHJ6.png

控制台错误消息的屏幕截图:https://imgur.com/a/IPq1FLP

更新 2

我现在单独发送标签,从而摆脱了“不允许的参数”。但是,如果条目无效,我仍然会收到一条无用的错误消息,而不是说明缺少必填字段:

Started POST "/projects/" for ::1 at 2021-01-03 01:42:21 +0100
Processing by ProjectsController#create as JSON
  Parameters: {"project"=>{"name"=>nil,"proto_url"=>nil},"tags"=>[]}
  User Load (0.3ms)  SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2  [["id",1]]
No template found for ProjectsController#create,rendering head :no_content
Completed 204 No Content in 6ms (ActiveRecord: 0.3ms | Allocations: 3920)

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...