Trouble with sending data from react to node

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



Trouble with sending data from react to node



I'm trying to build a website where user post queries and other users are able to answer in it. I'm trying to implement various tags in it using react-tags-input module. However i'm having problem in sending those tags to node server. Help needed.


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;



server file - I'm able to get userquery and image but req.body.tags is returning an empty object.


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")
);



Edited


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)
);



output


tags are:-





What is your this.state in onSubmit handler? If it is OK then what is your request body in browser dev tools?
– amankkg
Aug 8 at 16:12



this.state


onSubmit





Everything is same as in sandbox. Don't know what is going wrong.
– Rahul agrawal
Aug 9 at 6:59





Ya, finally found the issue. Thank you so so much for your help :)
– Rahul agrawal
Aug 9 at 8:16




1 Answer
1



The problem is in react-tags storing selected tags as a bunch of span elements, not input. So, these values are not included in form data being submitted.


react-tags


span


input



You have to handle form submit logic manually.

Here is an example of handlers you need to add/change:


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



Working example is in this sandbox.

Result is here: https://prnt.sc/kg2j9p



Update: now codesandbox uses fetch and posts the form data, you can try to submit form and see outgoing request in network tab in browser dev tools.





Tried to use fetch with method POST on onSubmit method, but still it gives empty object in server. Can you please show me by submitting tags on the server.
– Rahul agrawal
Aug 8 at 6:30





@Rahulagrawal check out updated codesandbox
– amankkg
Aug 8 at 7:56





ya, but don't know why bodyparser is not extracting the body. when i submit it and check req.body, it gives
– Rahul agrawal
Aug 8 at 9:02





@Rahulagrawal a-ha, seems like you're not sending headers: 'Content-Type': 'application/json'. In reality, you might need other configs also: cookies, cors, cache, etc. So, to simplify things, I skipped them since it's specific to your setup :) I updated my answer.
– amankkg
Aug 8 at 11:08



headers: 'Content-Type': 'application/json'





I've edited post. Can you check what am i going wrong with.
– Rahul agrawal
Aug 8 at 15:16






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

How to determine optimal route across keyboard