I've a trival web app up and running, where the use case is to interact with a single form:
Input text into input
Check a radio button
Upload a file
The server processes file upload, and saves to the directory.
However, when it comes to extract data from the request body, i'm running into problems, namely a 'cannot select property' error.
I'm using Express, with Bodyparser and Multer middleware. Please find source code below
var express = require('express'),
bodyParser = require('body-parser'),
multer = require('multer'),
MongoClient = require('mongodb').MongoClient,
assert = require('assert'),
formidable = require('express-formidable');
//var multipart = require('connect-multiparty');
var app = express();
//app.use(bodyParser.urlencoded({extended: true}));
//app.use(bodyParser.json());
//app.use(formidable.parse());
//app.use(multer);
//app.use(require('connect').bodyParser());
//app.use(bodyParser.json()); // to support JSON bodies
//app.use(bodyParser.urlencoded({ extended: true })); // to support URL-encoded bodies
//app.use(bodyParser.json());
//app.use(bodyParser.urlencoded({ extended: true }));
// -------------------------------------------------
// file storage - multer.
var storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, './uploads');
},
filename: function (req, file, callback) {
// save the file name with date and CAT_TYPE, not cat type is not operative.
callback(null, file.fieldname + '-' + Date.now() + 'CAT_TYPE');
}
});
var upload = multer({ storage : storage}).single('userPhoto');
// -------------------------------------------------
// handle post data - file upload and get.cat
app.post('/upload', function(req,res){
console.log("request to upload image recevied . . .");
console.log("upload in progress . . .");
console.log("upload complete . . .");
console.log("req.catype() = " + req.cat);
console.log("req.catype() = " + req.body.cat);
console.log("req.catype() = " + req.body.filename);
// handle file persistence to disk.
upload(req,res,function(err) {
if(err) {
return res.end("Error uploading file.");
}
res.end("File is uploaded");
});
});
app.post("/", function (req, res) {
console.log(req.body.user.name)
});
app.get('/',function(req,res){
res.sendFile(__dirname + "/index.html");
});
app.get('/hello',function(req,res){
res.sendFile(__dirname + "/hello.html");
});
var listener = app.listen(3000, function(){
console.log('listening on port ' + listener.address().port);
});
<head>
<script src="js/blueimp-gallery.min.js" async></script>
<script src="js/bootstrap.min.js" async></script>
<script src="https://code.jquery.com/jquery-3.1.1.min.js" async></script>
<script src="js/script.js" async></script>
<link rel="stylesheet" href="css/blueimp-gallery.min.css">
<link rel="stylesheet" type="text/css" href="css/style.css" />
</head>
<body>
<div id="main">
<div class="navbar-wrapper" style="border: 12px solid black;">
<ul>
<li>Login</li>
<li>Sign up</li>
</ul>
</div>
<div>
<form
id = "uploadForm"
enctype = "multipart/form-data"
action = "/upload"
method = "post">
<input type="file" name="userPhoto" />
<input type="submit" value="Upload Image" name="submit">
<label>filename</label>
<input type="text" value="input filename here" name="filename">
<label>travel</label>
<input type="radio" value="travel" name="cat">
<label>food</label>
<input type="radio" value="food" name="cat">
<label>community</label>
<input type="radio" value="community" name="cat">
</form>
</div>
<br>
<br>
<br>
<br>
</div>
</div>
<div id="filter">
<p>filter by content here.</p>
</div>
</body>
In short: bodyparser and multer cannot handle processing multipart uploads in the case of file data and form fields. This is achievable using other middleware ( I have successfully got this case working using formidable)
Related
My goal is to send emails with nodemailer, so I need to do that from my backend. I have a form in my vue component and I'm trying to send the data to http://localhost:3000/ but I get an error : POST http://localhost:3000/ 404 (Not Found). I'm using Axios to do that.
When I make a get request I get a response without any errors, but I cannot make a post request.
First, I created a server just to deploy my site on heroku (responsive proposes), but now I'm not sure if my backend configuration is ok to receive data from my client side. I looked around but I didn't find a specific answer to my problem.
Contact.vue:
<form class="form" #submit.prevent="sendData">
<ul>
<li>
<label for="name">Name</label>
<input type="text" id="name" name="user_name" v-model="name">
</li>
<li>
<label for="mail">E-mail</label>
<input type="email" id="mail" name="user_email" v-model="email">
</li>
<li>
<label for="msg">Message:</label>
<textarea id="msg" name="user_message" v-model="message"></textarea>
</li>
</ul>
<button type="submit" class="btn">Send</button>
</form>
<script>
import * as axios from 'axios';
export default {
data(){
return{
name: "",
email: "",
message: ""
}
},
methods: {
sendData(){
console.log(this.name, this.email,this.message);
axios.post("http://localhost:3000/",{
name: this.name,
email: this.email,
message: this.message
})
.then(response => {
console.log(response)
})
.catch(error =>{
this.error = error;
})
}
}
}
</script>
My server.js:
const express = require('express');
const port = process.env.PORT || 3000;
var cors = require('cors')
const app = express();
app.use(cors())
app.use(express.static(__dirname + "/dist/"));
app.get("/", function(req, res) {
res.sendfile(__dirname + '/dist/index.html');
})
app.listen(port);
console.log('Server started...');
You are sending a POST request to http://localhost:3000/, but this is set as a GET in your server. So try:
app.post("/", function(req, res) {
res.sendfile(__dirname + '/dist/index.html');
})
I want to convert a wav file to text using speech-to-text on IBM Cloud.
How do I send a request to get results for two channels?
Do I use websocketAPI?
If so, is there a channel specification in the parameters?
Can anyone tell me?
Thank you for your reply.
I am trying websocket connection with javascript.
In the following program, there is no response of "websocket.send (blob);".
Is the information corresponding to the blob incorrect?
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8" />
<script>
var websocket = null;
function start() {
var IAM_access_token = "{my-token}";
var wsURI = 'wss://gateway-tok.watsonplatform.net/speech-to-text/api/v1/recognize'
+ '?access_token=' + IAM_access_token
+ '&model=ja-JP_BroadbandModel';
console.log(wsURI);
websocket = new WebSocket(wsURI);
websocket.onopen = function(evt) { onOpen(evt) };
websocket.onclose = function(evt) { onClose(evt) };
websocket.onmessage = function(evt) { onMessage(evt) };
websocket.onerror = function(evt) { onError(evt) };
}
function onOpen(evt) {
var message = {
'action': 'start',
'content-type': 'audio/wav'
};
console.log(JSON.stringify(message));
websocket.send(JSON.stringify(message));
}
function onClose(evt) {
websocket.close();
}
function onMessage(evt) {
console.log(evt);
}
function onError(evt) {
console.log(evt);
}
function sendfile() {
console.log("send click!");
console.log(document.getElementById( "data" ));
var blob = document.getElementById( "data" );
websocket.send(blob) ;
}
</script>
</head>
<body>
<form method="post" enctype="multipart/form-data">
<div id="wrap">
<button type="button" onclick="start();">start</button>
<input type="file" id="data" name="data">
<button type="button" id="send" onclick="sendfile();">send</button>
</div>
</form>
</body>
</html>
I am new to web development. I am working in development of an angular application. I have developed an Angular form in front end, Node.js and Sql server in backend. I need some help to connect my angular form to the sql server database. I want to save the data from my angular form to my sql server database.
Versions:
Angular CLI: 8.0.3
Node: 10.16.0
OS: win32 x64
Angular: 8.0.1
I have tried using the restful api to insert data through the server page using post and get.
How can i to connect my angular form to sql databse and insert and update the data when the submit button in my angular form is clicked.
var express = require("express");
var bodyParser = require("body-parser");
var tediousExpress = require("express4-tedious");
var path = require("path")
var app = express();
// Body Parser Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
//CORS Middleware
app.use(function (req, res, next) {
//Enabling CORS
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, contentType,Content-Type, Accept, Authorization");
next();
});
app.get('/', function (req, res) {
var sql = require("mssql");
// config for your database
var config = {
server:'******',
database: '*******',
user:'******',
password: '*****',
};
// connect to your database
sql.connect(config, function (err) {
if (err) console.log(err);
// create Request object
var request = new sql.Request();
// query to the database and get the records
request.query('select * from dbo.contact', function (err, recordset) {
if (err)
console.log(err)
else
// send records as a response
res.send(recordset);
});
});
});
app.use("/contact", (req, res) => {
res.sendfile( __dirname + "/src/app/contact/contact.component.html");
});
app.use("/product", (req, res) => {
res.sendfile( __dirname + "/src/app/product/product.component.html");
});
app.use("/homepage", (req, res) => {
res.sendfile( __dirname + "/src/app/home/home.component.html");
});
const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Listening on port ${port}....`));
<div style="text-align:center">
<h1 class="well">
We are available here for you
</h1>
<div class="loader" *ngIf="dataloading"></div>
<div class = "row">
<div class="column">
<div class ="container">
<div class="col-md-5">
<div class="form-area">
<form role="form" (ngSubmit)="processForm()">
<br style="clear:both">
<h3 style="margin-bottom: 50px; text-align: center;">Contact</h3>
<div class="form-group">
<input required ngModel name="Name" #FirstName="ngModel" (change)="log(Name)" type="text" class="form-control" id="Name" name="name" placeholder="Name" [(ngModel)]="name" required>
<div class="alert alert-danger" *ngIf="Name.touched && !Name.valid" > Name is required.</div>
</div>
<div class="form-group">
<input required type="email" class="form-control" id="email" name="email" placeholder="Email" [(ngModel)]="email" required>
<div class="alert alert-danger" *ngIf="email.touched && !email.valid" > Email is required.</div>
</div>
<div class="form-group">
<input type="phone" class="form-control" id="mobile" name="mobile" placeholder="Mobile Number" [(ngModel)]="mobile" required>
</div>
<div class="form-group">
<input type="text" class="form-control" id="subject" name="subject" placeholder="Subject" [(ngModel)]="subject" required>
</div>
<div class="form-group">
<textarea class="form-control" type="textarea" id="message" name="message" placeholder="Message max(200)" [(ngModel)]="message" maxlength="140" rows="7"></textarea>
</div>
<hr class="mb-4">
<button type="button" id="submit" name="submit" class="btn btn-primary btn-lg btn-block" (click)="save(name, email, mobile, subject, message)">Submit</button>
</form>
</div>
</div>
</div>
````
````contact.component.ts
import { Component, OnInit} from '#angular/core';
import {HttpClient} from '#angular/common/http';
import {HttpErrorResponse} from '#angular/common/http';
import {Router} from '#angular/router';
#Component({
selector: 'app-contact',
templateUrl: './contact.component.html',
styleUrls: ['./contact.component.css']
})
export class ContactComponent {
title = 'Simple Example Contact-us page using Angular 4';
public data:any=[]
constructor(private http: HttpClient){
}
save(name, email, mobile, subject, message): void {
this.data['name']= name;
this.data['email']= email;
this.data['mobile']= mobile;
this.data['subject']= subject;
this.data['message']= message;
console.log(this.data);
//add request to send email or into mysql
this.http.post<any>('/contact1', this.data).subscribe(
res => {
console.log(res);
},
(err: HttpErrorResponse) => {
if (err.error instanceof Error) {
console.log("Client-side error occured.");
} else {
console.log("Server-side error occurred.");
}
});
}
}
````
I am using nodemailer to achieve myself sending emails from contact form.
My app.js looks like this
app.post('/jobs/join-us', (req, res) => {
console.log(req.body); //to return body
const output = `
<p>You have a new message from contact form.</p>
<h3>Contact Details</h3>
<ul>
<li>Name: ${req.body.name}</li>
<li>Email: ${req.body.email}</li>
</ul>
<h3>Message</h3>
<p>${req.body.message}</p>
`;
// create reusable transporter object using the default SMTP transport
let transporter = nodemailer.createTransport({
host: 'smtp.gmail.com',
port: 587,
secure: false, // true for 465, false for other ports
auth: {
user: 'xx', // generated ethereal user
pass: 'xx',
},
tls: {
rejectUnauthorized: false
}
});
// setup email data with unicode symbols
let mailOptions = {
from: 'xx', // sender address
to: 'xx', // list of receivers
subject: 'Contact Request', // Subject line
text: 'Hello world?', // plain text body
html: output // html body
};
// send mail with defined transport object
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
console.log(error);
res.end("error");
} else {
console.log('Message sent: %s', info.messageId);
//console.log('Preview URL: %s', nodemailer.getTestMessageUrl(info));
res.sendStatus(200);
}
});
});
Could anybody help me? I also try something like console.log(req) before const output but that didnt' return me anything viable.
This is my contact form itself, the POST request returns 200.
<div class='input-wrapper'>
<input class="flying-label-input" type="text" name="job_form[role]" id="job_form_role" />
<label class="flying-label required" for="job_form_role">Role</label>
</div>
<div class='input-wrapper'>
<input class="flying-label-input" type="text" name="job_form[email]" id="job_form_email" />
<label class="flying-label required" for="job_form_email">E-mail</label>
</div>
<div class='input-wrapper'>
<input class="flying-label-input" type="text" name="job_form[phone_number]" id="job_form_phone_number" />
<label class="flying-label" for="job_form_phone_number">Phone number</label>
</div>
<div class='input-wrapper'>
<label class="label required" for="job_form_cv">CV (PDF)</label>
<input type="file" name="job_form[cv]" id="job_form_cv" />
</div>
<div class='input-wrapper-space-top'>
<input type="hidden" name="job_form[referer]" id="job_form_referer" />
<input type="submit" name="commit" value="Submit Job Application" class="btn-round btn-primary" />
</div>
My app.js middleware functions:'
const express = require('express')
var app = express();
var path = require('path')
const nodemon = require('nodemon')
const nodemailer = require('nodemailer');
const bodyParser = require('body-parser');
// Static folder
app.use(express.static('public'))
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json())
The req.body is by default undefined so the fact that you get an empty object means that you are not populating the req.body with a body-parser and/or multer. This is also supported by the fact that the error-catching if statement does not return an error in the console so the req.body is there and it is an empty object. Try the following express middleware before your app.post and update the app.post as follows:
var app = require('express')();
var bodyParser = require('body-parser');
var multer = require('multer'); // v1.0.5
var upload = multer(); // for parsing multipart/form-data
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/jobs/join-us', upload.array(), function (req, res, next) {
console.log(req.body);
res.json(req.body);
});
while submitting a form without using ajax I could see "message sent successfully" in my http://localhost/ss (working fine as it should)
But while submitting a form using ajax $.post() response is not receiving to $.post() method. I couldn't find any reason..
Please note: same code works fine with php
index.html
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#buttons").click(function() {
$.post("http://localhost:3000/ss", {
sendemail: $("#email").val(),
sendname: $("#UserName").val(),
sendpass: $("#Password").val()
}, function(res) {
alert(res);
});
});
});
</script>
<body>
<div class="forms">
<form>
<div class="formdiv">
<label>User Email</label>
<input type="email" id="email" name="email" />
</div>
<div class="formdiv">
<label>User Name</label>
<input type="text" name="UserName" id="UserName" />
</div>
<div class="formdiv">
<label>User Password</label>
<input type="password" name="Password" id="Password" />
</div>
</form>
<div style="background:green;padding:15px;" id="buttons">send</div>
</div>
</body>
</html>
parse.js
var express = require("express");
var bodyParser = require("body-parser");
var app = express();
app.listen(3000, function(req, res)
{
console.log("express is listening to port 3000");
});
app.use(bodyParser.urlencoded({
extended: true
}))
app.use(bodyParser.json());
app.get("/", function(req, res)
{
res.send("hai");
});
app.post("/ss", function(req, res)
{
var ss = req.body.sendemail;
if (ss != undefined)
{
console.log(ss);
res.send("message sent successfully");
}
else
{
res.send("error occurred");
}
});
console prints user's email address "The only problem is response to html"
Code looks okey by itself, although there's one issue, with (i suspect) the way you use it. You're not allowing for cross-origin sharing. In other words, if you'd try to run this code on another domain, you'd receive a CORS error, as server refuses to respond to the client.
Therefore, I suspect you're loading the .html file either:
As local, html file.
Are running it from different domain
both of those would (and are) returning mentioned above error. That's why you're not receiving the response, so you're not seeing the alert message.
In order to bypass the issue, you can either:
Enable CORS support
Render HTML file through the server (so request will be coming from the same domain).
Example here:
var express = require("express");
var bodyParser = require("body-parser");
var app = express();
var path = require("path");
...
app.get("/", function(req, res)
{
res.sendFile(path.join(__dirname + '/index.html'));
});
app.post("/signup", function(req, res)
{
var email = req.body.email;
if (!email)
{
return res.json({
message: "error occurred"
});
}
res.json({
success: true;
});
});