gpt4 book ai didi

node.js - 从 react 到 Node 发送数据时出现问题

转载 作者:太空宇宙 更新时间:2023-11-03 22:07:27 25 4
gpt4 key购买 nike

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

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),
},
)
}

服务器.js

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

输出

tags are:- {}

最佳答案

问题在于 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使用获取并发布表单数据,您可以尝试提交表单并在浏览器开发工具的网络选项卡中查看传出请求。

关于node.js - 从 react 到 Node 发送数据时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51730026/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com