Form data in self.body is null. I am using Preact and Total js. value="#{M.email}" is not working. It populates the form with this value - preact

submitHandler is the function that I call onSubmit and sending data using XMLHttpRequest. I am sending data using xhr.Send() but in the controller, in self.body I am getting null values.
class Form extends Component {
render(props, state) {
<div>
<div class="field">
<label class="label">PHONE NUMBER</label>
<div class="control">
<input
class="input"
type="tel"
placeholder="+91 "
name="phone"
value="#{M.phone}"
onInput={linkstate(this, "phone")}
/>
</div>
</div>
</div>;
}
}
export default Form;
submitHandler = () => {
let formData = new FormData(document.getElementById("signup"));
let xhr = new XMLHttpRequest();
xhr.open("POST", "/xhr", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
console.log("Request finished");
}
};
xhr.onload = () => {
alert(xhr.responseText);
};
xhr.send(formData);
};

Are you sure that formData contains some data? Check the request in web developer tools and try to catch data.

Self.body from my understanding requires a JSON object. I converted the formData into a JSON object and it works.
xhr.send(JSON.stringify(Object.fromEntries(formData)));

Related

File upload (with other inputs and textarea) using Angular 13 and Node Js

I am trying to upload files to server using Angular and Node, using multer.
I have Todo Model as :
export class TodoModel {
todo_id !:number;
todo_title !:string;
todo_description !:string;
todo_status !:number;
todo_deleted_flag !:boolean;
todo_image !:Object;
}
todo.component.ts
title:string;
desc:string;
selected_image:File = null;
fileUploadListener(event){
//console.log(event)
//console.log(event.target.files[0])
this.selected_image = <File>event.target.files[0]
console.log(this.selected_image)
}
onSubmit(form:NgForm){
const fd = new FormData()
if(this.selected_image) {
fd.append('todo_image',this.selected_image,this.selected_image.name)
}
console.log(fd);
const todo_model : TodoModel = {
todo_id: null,
todo_title:this.title,
todo_description:this.desc,
todo_status:1,
todo_deleted_flag:false,
todo_image:null
}
console.log(fd);
this.todoAdd.emit(todoadded);
this.todoAdd_DB.emit(todo_model);
this.addTodo_DB(todo_model, fd)
form.resetForm();
}
addTodo_DB(todo_db: TodoModel, fileUpload:Object){
//const todo_db
return this.http.post<{message:any}>('http://localhost:3000/api/todos/post_all_todos_db', todo_db,fileUpload).subscribe(data => {
console.log(data.message);
console.log(todo_db);
})
}
todo.component.html
<div class="col-md-12">
<form (ngSubmit)="onSubmit(todoForm)" #todoForm="ngForm">
<div class="mb-3">
<label for="todo_title" class="form-label">Title</label>
<input type="text" class="form-control" id="todo_title" [(ngModel)]="title" name="title">
</div>
<div class="mb-3">
<label for="label" class="form-label">Description</label>
<textarea class="form-control" id="todo_description" [(ngModel)]="desc" name="desc"></textarea>
</div>
<div class="mb-3">
<label for="todo_image" class="form-label">Image</label>
<input type="file" class="form-control" id='todo_image' (change)="fileUploadListener($event)">
</div>
<button type="submit" class="btn btn-success">Add To Do</button>
</form>
</div>
</div>
And on Server Side, using Node Js and PgSQL :-
app.post('/api/todos/post_all_todos_db',upload_using_multer.single('todo_images') , (req, res, next) => {
// const todo_post = req.body;
const files = req.file;
console.log(files) // - ----------> This does NOT work
console.log(req.body) //------> this works
//PGSQL insert query here
res.status(201).json({
message:"Post Added Successfully"
})
})
While doing console.log() in Angular side, I am getting the form data, but, on Node Js side, I get it as null.
Almost every tutorial I see, uses only one file upload , and that too, try to submit the form using the Form's action. I dont want to do that, so I tried doing this.
I
i once had the same issue and solved it with formdata, my example uploads multiple files. here is an example:
Node.JS
const serverRoutes = (function () {
const express = require('express');
const router = express.Router();
const multer = require('multer');
const upload = multer();
router.post('/myresource', upload.any(), (req, res) => {
console.log(req.files);
});
return router;
});
on angular
export class DataService {
constructor(private http: HttpClient) { }
sendMyFiles(file): Observable<MyResponse> {
const formData = new FormData();
formData.append("file", file);
return this.http.post<MyResponse>(
`${environment.backendAPI}myresource`,
formData
);
}
}

Search documents from MongoDB with Angular

I am trying to do a bar search to search users from a collection in MongoDB with Angular. I already did the function in the server side and it's working with Postman, but in the client side i am getting this error: "Http failure response for http://localhost:3800/api/find/: 0 Unknown Error"
this is my code on the server side
function findUser(req, res) {
let params = req.body;
User.find(
{
$or: [
{nick : new RegExp(params.word, 'i')},
{name : new RegExp(params.word, 'i')}
]
}, function (err, docs) {
return res.json(docs);
});
and the route
api.post('/find', md_auth.ensureAuth, UserController.findUser);
this is my code on the client side
user.service
findUser(word): Observable<any>{
let params = JSON.stringify(word);
let headers = new HttpHeaders().set('Content-Type', 'application/json').set('Authorization', this.getToken());
console.log(params);
return this._http.post(this.url+'find/', params, {headers: headers});
}
user controller
#ViewChild('word') wordS:ElementRef;
findUser(){
this.word = this.wordS.nativeElement.value;
console.log(this.word);
this._userService.findUser(this.word).subscribe(
response => {
console.log(this.word);
console.log(response);
}, error => {
var errorMessage = <any>error;
console.error(errorMessage);
}
)
}
and html (view)
<form class="form-inline">
<input #word class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success my-2 my-sm-0" (click)="findUser()" type="submit">Search</button>
</form>
JSON.stringify() doesn't return an object. It returns a string.
The server-side function is looking for a property called word in the request body.
If you post an object in your user.service instead of just a string...
...,
return this._http.post(this.url+'find/', { word: params }, headers);
Your function should work. However, you don't really need to call JSON.stringify if you're already passing a string to your service method.
Alternatively, if you're using a reactive form, you can just pass the form.value of your FormGroup instance to your service method, which will be an object, e.g. { word: 'some value' }, which can then be passed as the POST data as-is.

Show added posts without refreshing page in React

I have been working on a personal project outside university, developing a blog.
Right now I'm trying to implement a "home page" where after a succesfull login, the user can post text, and right after that it appears under the Create post div you can see in the pic
This is what I have managed to accomplish so far:
This is the home page after login
Right now I can login, and post a new post which saves it in the database.
This is the home.js functional componenet which the user sees after a login:
import '../App.css';
import { useHistory } from "react-router-dom";
import React , {useState, useEffect} from 'react';
import jwt_decode from 'jwt-decode'
import logo from '../images/home-logo.png';
import {Col,Form,Input,Button,Card,CardTitle,Navbar,Nav,NavbarBrand} from 'reactstrap'
import { createPost,getUserPosts } from '../fucntions/user_functions'
function Home(){
var _decoded;
var _email;
let history = useHistory();
const[post_text,setPost] = useState('');
const handleChangePost = e =>{ setPost(e.target.value);};
function handlePost(e){
e.preventDefault();
const toPost = {
post :post_text, email :_email
}
createPost(toPost).then(res =>{
setPost('')
})
}
function getPosts() {
const container ={
email:_email
}
getUserPosts(container).then(res=>{
})
}
function handleLogout (e) {
e.preventDefault();
localStorage.removeItem('usertoken')
history.push(`/login`)
}
useEffect(() =>{
if (localStorage.getItem("usertoken") === null) {
history.push('/login')
} else {
const token = localStorage.usertoken
const user_email = localStorage.useremail
const decoded = jwt_decode(token)
_decoded = decoded;
_email = decoded.email
getPosts()
};
});
return (
<div className = "box">
<div>
<Navbar color="light" light expand="md">
<Nav>
<NavbarBrand type = "button" onClick = {handleLogout}>Logout</NavbarBrand>
</Nav>
</Navbar>
<div className = "wrapper">
<Card body outline color="secondary" className = "card-home " >
<CardTitle><img src={logo} alt="logo"></img>Create post</CardTitle>
<Form onSubmit = {handlePost}>
<Input id = "tx" name = "input1" type = "textarea" value = {post_text} placeholder="Enter your post here" onChange= {handleChangePost}></Input>
<br></br>
<Col sm={{ span: 10, offset: 5 }}>
<Button outline color="primary" type="submit">Post!</Button>
</Col>
</Form>
</Card>
</div>
</div>
</div>
)
}
export default Home;
I have implemented a getPosts method in the backend which gives back an array of the posts
router.post("/getPosts",
async (req, res) => {
const {email,} = req.body;
try {
let user = await User.findOne({email:email});
allPosts = user.posts
res.render('/home',{posts : hello})
} catch (e) {
console.error(e);
res.json("Error")
}
}
);
As you can see above, in the function getPosts(), the response is an Array of all the post's ids the user has posted, they are stored in the mongodb collection called "posts"
And after calling that function, I can iterate over them:
function getPosts() {
const container ={
email:_email
}
getUserPosts(container).then(res=>{
forEach(res.posts) {
}
})
}
I want to render all those posts live, so each time the user posts a new post, it will show right after the Create post div you can see in the picture, What's the best way?
Thanks
First define your posts collection state:
const [allPosts, setAllPosts] = useState([]);
Then every time you successfully save a post in the database, append it to that state:
function handlePost(e){
e.preventDefault();
const toPost = {
post :post_text, email :_email
}
createPost(toPost).then(res =>{
setPost('')
setAllPosts(allPosts.concat(toPost);
})
}
The same goes for getPosts:
function getPosts() {
const container ={
email:_email
}
getUserPosts(container).then(res=>{
setAllPosts(res.data); // <-- if the data is the same structure as the created before
})
}
Then you can render them in an example way:
return (
<div className = "box">
<div>
<Navbar color="light" light expand="md">
<Nav>
<NavbarBrand type = "button" onClick = {handleLogout}>Logout</NavbarBrand>
</Nav>
</Navbar>
<div className = "wrapper">
<Card body outline color="secondary" className = "card-home " >
<CardTitle><img src={logo} alt="logo"></img>Create post</CardTitle>
<Form onSubmit = {handlePost}>
<Input id = "tx" name = "input1" type = "textarea" value = {post_text} placeholder="Enter your post here" onChange= {handleChangePost}></Input>
<br></br>
<Col sm={{ span: 10, offset: 5 }}>
<Button outline color="primary" type="submit">Post!</Button>
</Col>
</Form>
<div>
{
allPosts.map(post => {
return <div><div>email: {post.email}</div><div>post: post.post</div></div>
})
}
</div>
</Card>
</div>
</div>
</div>
)
Feel free to change the HTML structure, so it matches your design

How do I have a variable available to display on my success page, after adding items to a database via a /POST route?

I would like to display the doc.id variable of a successful /POST of data to a route, on the success page that the user will be redirected to afterward. I'm trying to work out how to carry the variable teamId through to the Handlebar template page success.hbs
I've tried making it a variable, and setting up a Handlebar helper to display it, but nothing is working.
/POST route redirecting to success.hbs:
app.post('/create', (req, res) => {
var players = [];
var playerObj = {};
for (let i = 1; i < 21; i++) {
var playerObj = { playerName: req.body[`player${i}Name`], playerNumber: req.body[`player${i}Number`], playerPosition: req.body[`player${i}Position`] };
if (req.body["player" + i + "Name"] === '') {
console.log("Empty player name detected, disregarding");
} else {
players.push(playerObj);
}
}
var newTeam = new Team({
// WEB SETUP BELOW
"team.teamRoster.teamCoach": req.body.coachName,
"team.shortTeamName": req.body.teamShortName,
"team.teamName": req.body.teamName,
"team.teamRoster.players": players
});
newTeam.save().then((doc) => {
var teamId = doc.id;
console.log(teamId);
res.render('success.hbs');
console.log("Team Added");
}, (e) => {
res.status(400).send(e);
});
});
/views/success.hbs
<div class="container-fluid" id="body">
<div class="container" id="page-header">
<h1><span id="headline">Team Added Succesfully</span></h1>
<hr>
<h3><span id="subheadline">Input the following address as a JSON Data Source within vMix.</span></h3>
<span id="content">
<div class="row">
<div class="container col-md-12">
{{{teamId}}}
</div>
</div>
</span>
</div>
<hr>
</div>
I'd like a Handlebar helper to get the doc.id value of the /POST request, and store it as teamId to display on the success page. It's finding nothing at the moment.
Any help is appreciated.
Node.js can pass variables to the handlebars-view like this:
newTeam.save().then((doc) => {
var teamId = doc.id;
console.log(teamId);
res.render('success.hbs', {
teamId
});
console.log("Team Added");
}, (e) => {
res.status(400).send(e);
});

How to send a large datauri of an image to express server

I have the daturi of an image which is uploaded from the desktop.I would like to send this data uri to express server so as to save the dataUri in a text file. Since the size of the data uri of the image is quite large I am getting payload too large error which is understandable. I tried using multer but I couldn't figure out how to extract the data uri of the image when multer is used, on the server side.Any help on this is greatly appreciated.
Below is some of the code sample that I am trying to use
<div class="row">
<div class="form-group">
<label class="btn btn-default btn-file" for="FileUpload">Upload a Plan</label>
<input type="file" id ="FileUpload" accept="image/*" capture="camera" value="" onchange="readFileURL(this);" style="display: none;">
<img id="chosenFile" src="#" style="visibility: hidden;"/>
</div>
</div>
<div class="row">
<div class="col-sm-12"><button style="background-color: green" class="btn btn-default btn-sm" onclick="handleUplod(this)">Upload</button></div>
</div>
<script type="text/javascript">
function readFileURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
document.getElementById("chosenFile").style.visibility="visible";
reader.onload = function (e) {
$('#chosenFile').attr('src', e.target.result).width(150).height(150);
console.log("result:",e.target.result);
imageData = e.target.result;
};
console.log("data url:"+reader.readAsDataURL(input.files[0]));
}
};
function handleUplod(){
$.ajax({
type: "POST",
url: "/send",
data: { MyPlanDataUri:imageData },
success: function(result){
location.href= "/someplace";
},
error: function(result) {
alert('error');
}
});
};
On the server side I am doing the following
app.post('/send', function(req,res) {
var Tex1 = req.body.MyPlanDataUri;
var newFile = "ImageFile.txt";
fs.writeFile(newFile, Tex1, (err) => {
if (err) res.send(err);
console.log('File saved successfully ! - ', newFile);
}
);
res.send("Successfull");
}
P.S the above code works perfectly fine for small datauri's

Resources