【问题标题】:Trouble with sending data from react to node从反应发送数据到节点的问题
【发布时间】:2019-01-14 17:39:00
【问题描述】:

我正在尝试建立一个用户发布查询和其他用户能够在其中回答的网站。我正在尝试使用 react-tags-input 模块在其中实现各种标签。但是我在将这些标签发送到节点服务器时遇到问题。需要帮助。

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { Link } from 'react-router-dom';
import '../Login.css';
import "./Home.css";
import Post from "./Post";
import { WithContext as ReactTags } from 'react-tag-input';

const KeyCodes = {
  comma: 188,
  enter: 13,
};

const delimiters = [KeyCodes.comma, KeyCodes.enter];

class query extends Component {

  constructor() {
    super();
    this.state = {
      userquery:'',
      queries:[],

      tags: [],
    suggestions: [
        { id: "Javascript", text: "Javascript" },
        { id: "Java", text: "Java" },
        { id: 'node.js', text: 'node.js' },
        { id: 'react.js', text: 'react.js' },
        { id: 'express', text: 'express' },
        { id: 'bootstrap', text: 'bootstrap' },
        { id: 'python', text: 'python' },
        { id: 'c++', text: 'c++' }
     ]
    };

    this.handleDelete = this.handleDelete.bind(this);
    this.handleAddition = this.handleAddition.bind(this);
    this.handleDrag = this.handleDrag.bind(this);
  }

  onChange = (e) => {
    const state = this.state
    state[e.target.name] = e.target.value;
    this.setState(state);
  }

componentDidMount(){
  fetch('/query').
    then((Response)=>Response.json()).
    then(data =>{
        this.setState({queries:data.reverse()}); 
    })

}

handleDelete(i) {
  const { tags } = this.state;
  this.setState({
   tags: tags.filter((tag, index) => index !== i),
  });
}

handleAddition(tag) {
  this.setState(state => ({ tags: [...state.tags, tag] }));
}

handleDrag(tag, currPos, newPos) {
  const tags = [...this.state.tags];
  const newTags = tags.slice();

  newTags.splice(currPos, 1);
  newTags.splice(newPos, 0, tag);

  // re-render
  this.setState({ tags: newTags });
}


  render() {
    const {userquery } = this.state;
    const { tags, suggestions } = this.state;

    return (
      <div class="container">
        <form action="/queries" method="POST">
          <h2 class="form-signin-heading" color="blue">Want to ask something? ask here!</h2>
          <label for="inputQuery" class="sr-only">query</label> 
          <textarea type="text" class="form-control" placeholder="want to ask something? ask here!" name="userquery" required/>
          <br/>
          <div class="form-group ">
            <input class="form-control" type="text" name="image" placeholder="image url"/>
          </div>

          <div class="form-group ">
          <ReactTags 
              name='tags'
              tags={tags}
              suggestions={suggestions}
              handleDelete={this.handleDelete}
              handleAddition={this.handleAddition}
              handleDrag={this.handleDrag}
              delimiters={delimiters}
               />

        </div>
        <br/>
          <button class="btn btn-lg btn-primary btn-block" >Ask</button>
        </form>
        <section>
          <h2> Recent Posts</h2>
        </section>

        {this.state.queries.map((item, key) => {
          return (<Post item={item} key={key} />)
        }
      )
    }
      </div>

    );

  }
}

export default query;

服务器文件 - 我能够获取用户查询和图像,但 req.body.tags 返回一个空对象。

app.post("/queries",isLoggedIn,function(req,res){
        var postQuery =req.body.userquery;
        var userImages =req.body.image;
        console.log(req.body.tags);
        username=req.user.username;

        var newQuery = {
            name:username,
            image:userImages,
            description:postQuery
        }
        Query.create(newQuery,function(err,newlyCreated){
            if(err){
                console.log(err);
            }
            else{
                res.redirect("http://localhost:3000/home");
            }
        })
       // res.send("you hit the post route")
});

编辑

onSubmit = e => {
  e.preventDefault()
  const {someText, tags} = this.state
  const data = {someText, tags: tags.map(x => x.id)}
  alert(`Submitting: ${JSON.stringify(data)}`)

    fetch(
      'queries',
      {
        method: 'POST',
        mode: "cors", // no-cors, cors, *same-origin
        cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
        credentials: "same-origin",
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data),
      },
    )
 }

server.js

app.post("/queries",function(req,res){
 console.log("tags are:-",req.body)
});

输出

tags are:- {}

【问题讨论】:

  • this.stateonSubmit 处理程序中是什么?如果可以,那么您在浏览器开发工具中的请求正文是什么?
  • 一切都和沙盒一样。不知道怎么回事。
  • 嗯,终于找到问题了。非常感谢您的帮助:)

标签: node.js reactjs forms jsx


【解决方案1】:

问题在于react-tags 将选定标签存储为一组span 元素,而不是input。因此,这些值不包含在提交的表单数据中。

您必须手动处理表单提交逻辑。
以下是您需要添加/更改的处理程序示例:

onSubmit = e => {
  e.preventDefault() // stop default form submission
  const { field1, field2, tags } = this.state // select form input values to submit
  const data = { field1, field2, tags: tags.map(t => t.id) } // create an object to submit

  fetch(
    'url',
    {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(data),
    },
  ) // send POST request
}

onChange = e => this.setState({ [e.target.name]: e.target.value }) // for plain inputs

onAdd = tag => this.setState(state => ({ tags: [...state.tags, tag] })) // for tags input

render() {
  return (
    <form onSubmit={this.onSubmit}>
      <input name="field1" onChange={this.onChange} />
      <input name="field2" onChange={this.onChange} />
      <ReactTags
        tags={this.state.tags}
        handleAddition={this.onAdd}
      />
      <button type="submit">submit</button>
    </form>
  )
}

工作示例位于this sandbox
结果在这里:https://prnt.sc/kg2j9p

更新:现在codesandbox使用fetch并发布表单数据,您可以尝试提交表单并在浏览器开发工具的网络选项卡中查看传出请求。

【讨论】:

  • 尝试在 onSubmit 方法上使用 fetch 和方法 POST,但它仍然在服务器中提供空对象。你能通过在服务器上提交标签来告诉我吗?
  • 是的,但不知道为什么 bodyparser 不提取正文。当我提交它并检查 req.body 时,它给出了 {}
  • @Rahulagrawal a-ha,好像你没有发送headers: {'Content-Type': 'application/json'}。实际上,您可能还需要其他配置:cookies、cors、缓存等。因此,为了简化事情,我跳过了它们,因为它特定于您的设置:) 我更新了我的答案。
  • 我已经编辑了帖子。你能检查一下我出了什么问题吗?
猜你喜欢
  • 1970-01-01
  • 2020-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-09
  • 2019-09-07
  • 2021-07-07
  • 1970-01-01
相关资源
最近更新 更多