无法将数据从响应发送到节点

时间:2018-08-07 15:06:28

标签: node.js reactjs forms jsx

我正在尝试建立一个网站,供用户发布查询,其他用户可以在其中回答。我正在尝试使用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;

服务器文件-我能够获取userquery和图像,但是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:- {}

1 个答案:

答案 0 :(得分: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使用获取并发布表单数据,您可以尝试在浏览器开发工具的“网络”标签中提交表单并查看传出请求。