Sending POST data via AJAX to NodeJS server - javascript

I have made basic web apps whereby data is sent via HTTP parameters. However, I am trying to send data from client-side that contains an array (a list of ingredients for a recipe) and eventually, hopefully user uploaded image (but not worried about that for now). For this I know I need to use AJAX. I have spent hours trying to get it to work but for some reason, no POST request is being sent. The user inputs are fairly basic but here's a snippet:
<label for="method"> Method </label>
<textarea id="method" name="method">method here</textarea>
</br>
<p> add ingredients </p>
<input name="ingredient" id="ingredient" placeholder="add ingredient">
<input name="quantity" id="quantity" placeholder="#"><button id="addIngBtn" type="button">Add</button><br>
<button type="submit">submit</button>
<p> Ingredients:</p>
<ul id="ingredientListUL">
I use JQUERY to allow users to append as many ingredients as they want to the list:
$(document).ready(() => {
$("#addIngBtn").click(() => {
let ingredient = $("#ingredient").val();
let quantity = $("#quantity").val();
$("#ingredient").val(""); //reset ingredient input
$("#quantity").val("");
$("ul").append(
"<li>" + ingredient + " - " + quantity + "</li>"
);
});
})
Ingredients are built into an array and then added to a new recipe object which is the data I want to send to my server:
var ingredients = [];
$("#ingredientListUL li").each((index, element) =>
ingredients.push($(element).text())
)
var recipe = {
name: $("#name").val(),
image: $("#image").val(),
oneLiner: $("#oneLiner").val(),
method: $("#method").val(),
ingredients: ingredients
}
So far so good. I presume I am doing something wrong with these next parts. Here's the AJAX post request:
$.ajax({
url: "http://localhost:5000/recipes",
type: "POST",
dataType: "json",
data: recipe,
contentType: "application/json",
complete: function () {
console.log("process complete");
},
success: function (data) {
console.log(data);
console.log("process success");
},
error: function () {
console.log(err);
}
})
And here's my server info:
// express setup
const express = require("express");
const app = express();
const port = 5000;
// set templating engine to EJS
app.set('view engine', 'ejs');
// import route files
const recipeRoutes = require("./routes/recipes")
app.use("/recipes", recipeRoutes);
// body parser
const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json())
//--
// BASIC ROUTES
//--
app.get("/", (req, res) => res.render("landing"));
// Port
app.listen(port, () => console.log(`Server starting on port ${port}!`));
All routes, are stored in a recipe routes file, which contains the post route for this request:
// default "/" route is really "/recipes" as defined in main server file.
router.post("/", (req, res) => {
console.log(req.body.recipe);
})
The problem is that nothing appears to be sent to, or received by my server according to network tab. Even when I try to send something like:
$.post("http://localhost:5000/recipes", { test: "test" })
What am I doing wrong? Thanks.

The contentType property does not work that way. It indicates if it is URL encoded, as a multipart message, etc. Try removing it.
According to: https://api.jquery.com/jquery.ajax/ :
"If you explicitly pass in a content-type to $.ajax(), then it is
always sent to the server (even if no data is sent)"

Related

Connect node app and server + post image to server

I have a very basic question about a node application, and a question about HTTP requests. It's the first time I create a node app with server, and I just can't seem to get the different components to work together.
This is my server.js
var express = require('express');
var multer = require('multer');
const request = require('request');
const upload = multer({dest: __dirname + '/uploads/images'});
const app = express();
const PORT = 3000;
app.use(express.static('public'));
app.post('/upload', upload.single('photo'), (req, res) => {
if(req.file) {
res.json(req.file);
}
else throw 'error';
});
app.listen(PORT, () => {
console.log('Listening at ' + PORT );
});
Then I have a file app.js with a motion-detection system. Every time motion is detected, a picture is taken. This all works fine.
Then the picture should be sent to the server. This is what I can't figure out.
I created a function toServer() that should post the detected data to the server
const request = require('request');
function toServer(data) {
const formData = {
// Pass data via Buffers
my_buffer: data,
// Pass optional meta-data with an 'options' object with style: {value: DATA, options: OPTIONS}
// Use case: for some types of streams, you'll need to provide "file"-related information manually.
// See the `form-data` README for more information about options: https://github.com/form-data/form-data
};
request.post({url:'http://localhost:3000/upload', formData: formData}, function optionalCallback(err, httpResponse, body) {
if (err) {
return console.error('Upload failed:', err);
}
console.log('Upload successful! Server responded with:', body);
});
};
Problem 1: when running the server.js on localhost:3000, it doesn't find any of the scripts loaded in index.html nor my app.js.
Problem 2: when running the index.html on live-server, all scripts are found, but i get the error "request is not defined".
I am pretty sure there is some basic node setup thing I'm missing.
The solution for toServer() might be more complicated.
Thanks for your time,
Mustard Shaper
Problem 1:
this could happen because you have not specified to render your index.html.
for example:
res.render('index')
if it's not because of the single quotes in upload.single('photo') try double quotes.
Another possible error could be that you are missing a default display engine setting.
an example: https://www.npmjs.com/package/hbs
Problem 2:
it may be because you are missing the header
var request = require('request');
request.post({
headers: {'content-type' : 'application/x-www-form-urlencoded'},
url: 'http://localhost',
body: "example"
}, function(error, response, body){
console.log(body);
});
See more at https://expressjs.com/

Fetch API POST to Node-js only 6 times

I was trying to use the Fetch API POST method in Vanilla JS. The endpoint was located in Node-JS code.
The POST method function run whenever ONKEYDOWN function runs on html text input. Whenever we type on keyboard, it sends data to the Node-JS Endpoint and then prints it. Each time I typed, the data was being sent but was only received only 6 times before it stopped printing the req.body.
Here's is my code for HTML + Vanilla JS (index.html).
<div onkeydown="post()">
First Name
<input type="text" name="FirstName" id="FirstName">
<br> <br>
Middle Name
<input type="text" name="MiddleName" id="MiddleName">
<br> <br>
Last Name
<input type="text" name="LastName" id="LastName">
</div>
<script>
function post() {
const formData = {
FirstName: document.getElementById('FirstName').value,
MiddleName: document.getElementById('MiddleName').value,
LastName: document.getElementById('LastName').value,
}
localStorage.setItem("FirstName", formData.FirstName)
localStorage.setItem("MiddleName", formData.MiddleName)
localStorage.setItem("LastName", formData.LastName)
console.log(formData);
fetch('/', {
method: 'post',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(formData)
})
}
</script>
Here's is my Code for Node-js (index.js)
const express = require('express')
const app = express()
app.use(express.json({ limit: '20mb'}))
app.use(express.static('/')) //static folder
app.listen(80, () => {
console.log('THE PORT IS UP AND RUNNING')
})
app.get('/', (req, res) => {
res.sendFile('index.html', { root: __dirname })
})
let i = 0; // to display the number of outputs
app.post('/', (req, res) => {
console.log(req.body, i++)
// print the data
})
According to this code, I recieve the req.body only for 6 times which is printed in the terminal (6 times). Please help
You need to send response to previous requests.
The easiest way to achieve it is to call .end() method of the res object
// print the data
res.end();
Your requests don't hit the server due to browser's concurrent requests limit which is 6 for some browsers including Google Chrome. Browser waits for pending requests to finish before sending next ones, but your server never sends response.

Javascript - Send User Input from front-end to back-end server

I have an input field where the user enters a location, once the submit button is pressed, I can capture the data that the user entered as newLocation. However, I need to send this data to the back-end server and I am not sure how. I guess one way is to use axios.post and axios.get - but I am not quite sure how to implement that. See both front-end and back-end code below:
Front-end:
import store from "../src/store";
import axios from "axios";
const RenderButton = () => {
async function captureText() {
const locationName = document.getElementById("locationName");
let newLocation = locationName.value;
store.dispatch({ type: "locationUpdate", payload: newLocation });
}
return (
<div id="submit">
<h2>Enter Location</h2>
<input type="text" id="locationName" />
<button id="submitButton" onClick={captureText}>
Submit Location
</button>
</div>
);
};
export default RenderButton;
Back-end:
const path = require("path");
const axios = require("axios");
const app = express();
app.use("/dist", express.static(path.join(__dirname, "dist")));
app.use("/public", express.static(path.join(__dirname, "public")));
app.get("/", async (req, res, next) =>
res.sendFile(path.join(__dirname, "index.html"))
);
Axios would not be needed on the backend. You just need to set up a route in express, just like the / one that returns the html. It can take request parameters such as form data. Something like this:
app.get('/endpoint', function (req, res) {
console.log(req.body)
})
See for formdata parsing: https://stackoverflow.com/a/38763341/13357440
Also: https://expressjs.com/en/guide/routing.html
As for the frontend, many options exist that can send a request and get a response without redirecting. XMLHttpRequest (ajax) is one of the more popular ones. https://developer.mozilla.org/en-US/docs/Web/Guide/AJAX/Getting_Started#step_3_%E2%80%93_a_simple_example

Twilio JavaScript - SMS from client to server

I've found docs teaching on how to implement Twilio on server-side using Node, however, I couldn't find an end-end example where I can send a SMS coming from my client app.
Can anyone tell me what the implementation would look like to send a post custom SMS from client to server?
Disclaimer my server file is named as app.js and my client file is named as index.js
**1- This is what I have currently setup on my app.js
const express = require('express');
const app = express();
const path = require('path');
const twilio = require('twilio');
const bodyParser = require('body-parser');
//JSON DATA
const guests= require('./public/data/Guests');
app.use(bodyParser.urlencoded({extended: false}));
app.use(express.static('public'));
//SET PORT
app.set("port", process.env.PORT || 3000);
//GET JSON DATA
app.get('/data', function(req, res) {
Promise.all([guests])//combine requests into one object
.then(([guests]) => {
res.send({guests});
});
});
//CATCHALL
app.get("/*", function(req,res){
let file = req.params[0] || "/views/index.html";
res.sendFile(path.join(__dirname, "/public/", file));
});
//LISTEN ON PORT
app.listen(app.get("port"), function(){
console.log("Listening on port: " , app.get("port"));
});
let client = new twilio('xxxxxxxxxx', 'xxxxxxxxxxxxx');
app.post('/sms', (request, result) => {
const message = request.body.message;
client.messages.create({
to: +1847820802492359,
from: +8475302725792530 ,
body: message
}).then(() => {
// message sent successfully, redirect to the home page.
res.redirect('/');
}).catch((err) => {
console.error(err);
res.sendStatus(400);
});
});
-2 am trying to process a dynamic message in my index.js. The code works on the DOM properly, it is just the SMS with Twilio that isn't posting the message to the server
$(function() {
$.ajax({
type: "GET",
url: "/data",
success: res => {
//console.log(res);
handleMessage(res);
},
error: err => console.log(err)
});
//message method
let handleMessage = (res) => {
const getFirstName = res.guests.map(name => name.firstName);
//populate drop-down select
let handleSelect = () => {
//adds first names to select dropDown
$.each(getFirstName, function(i, value) {
$('#selectName').append($('<option>').text(value).attr('value', value));
});
};
handleSelect();
let handleSubmit = () => {
$("#form").submit(function(e) {
e.preventDefault();
let name = $('#selectName').val();
let greetGuest = `Welcome ${name}!`;
console.log(greetGuest);
//append to Dom
$('.showMessage').append(`<div class="newMessage"><span>${greetGuest}</span></div>`);
});
};
handleSubmit()
};
});
-3 HTML form
<form id="form" action="/sms" method="POST">
<label>
<label for=selectName>Guest
<select id="selectName" class="select " name="sms">
</select>
</label>
</label>
<input type="submit" value="send" class="btn btn-success" />
</form>
Am I having an asynchronicity issue here?
Twilio developer evangelist here.
I can give you a basic example here, which should give you a good idea of how to achieve this. I'll start with the server side, which you already have the basics of.
Firstly, I would recommend you use a POST request rather than a GET, simply because GETs can be easily repeated by users or cached by proxies. I assume you are using Express as the web application server. You will also need the body-parser module to read the data that we send from the client side.
const Twilio = require('twilio');
const express = require('express');
const bodyParser = require('body-parser');
const app = new express();
app.use(bodyParser.urlencoded({extended: false}));
app.use(express.static('public'));
const twilio = new Twilio(YOUR_ACCOUNT_SID, YOUR_AUTH_TOKEN);
app.post('/messages', (request, result) => {
const message = request.body.message;
twilio.messages.create({
to: TO_NUMBER,
from: FROM_NUMBER,
body: message
}).then(() => {
// message sent successfully, redirect to the home page.
res.redirect('/');
}).catch((err) => {
console.error(err);
res.sendStatus(400);
});
});
app.listen(3000);
This sets up a server which is serving static files from a public directory and then has one endpoint, POST to /messages, that sends a message.
We now need to create the client side. I shall do this in HTML only for simplicity. You need a form that will POST to the /messages endpoint with, in this case, a single field for the message. I've included a textarea to write the message in and a button to submit the form. If you save this as index.html in the public directory where you run the application from then it should work.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Send a message!</title>
</head>
<body>
<h1>Send a message!</h1>
<form action="/messages" method="POST">
<label for="message">What would you like to send?</label>
<textarea name="message" id="message"></textarea>
<button type="submit">Send!</button>
</form>
</body>
</html>
Let me know if that helps at all.
Update
So you're looking to make the request to the server using Ajax so your page doesn't reload and you can display a different message. Your current form seems to have removed the message textarea that I added, I'll put it back in again. I assume you also want to send the message to whichever guest you are welcoming at the time, but I don't know how that works in your system, so I'm going to avoid that for now and hopefully you can sort it out.
So, if you update your form to something like this:
<form id="form" action="/sms" method="POST">
<label>
<label for=selectName>Guest
<select id="selectName" class="select " name="sms">
</select>
</label>
</label>
<label for="message">Message</label>
<textarea id="message" name="message"></textarea>
<input type="submit" value="send" class="btn btn-success" />
</form>
Then you need to add to your JavaScript a way to actually submit the form (since you are preventing the submission with e.preventDefault().
const $form = $('#form');
$form.submit(function(e) {
e.preventDefault();
let name = $('#selectName').val();
let greetGuest = `Welcome ${name}!`;
console.log(greetGuest);
$.ajax({
url: $form.attr('action'),
type: $form.attr('method'),
data: $form.serialize(),
success: function(data) {
console.log("The message has been sent");
},
error: function() {
console.error("The message couldn't be sent");
console.error(...arguments);
}
})
//append to Dom
$('.showMessage').append(
`<div class="newMessage"><span>${greetGuest}</span></div>`
);
});
In this case we are hooking into the callback for the submit event to make a new $.ajax request to the form's action, using the method (POST), and including the form data (which we get from $form.serialize()). We then setup success and error callbacks as you've done at the top of the function.
Let me know if this helps.

getting empty body in record action - twilio

My use case:
My case is that i'm making a bot for listening podcast in which user will make call to twilio number and bot will ask what type of podcast would you like to listen then record for 10 seconds
when recording finish, it say user to please wait while we are finding podcast
I want that recording in my webhook so i will figure out caller mood and find appropriate podcast mp3 file from my database and play to caller
Issue I'm Facing:
I'm getting empty body in all of my webhooks
My code:
var express = require("express");
var bodyParser = require("body-parser");
var VoiceResponse = require('twilio').twiml.VoiceResponse;
var app = express();
var port = (process.env.PORT || 4000);
app.use(bodyParser.json())
// helper to append a new "Say" verb with alice voice
function say(text, twimlRef) {
twimlRef.say({ voice: 'alice' }, text);
}
// respond with the current TwiML content
function respond(responseRef, twimlRef) {
responseRef.type('text/xml');
responseRef.send(twimlRef.toString());
}
app.post("/voice", function (request, response, next) {
console.log("request: ", request.body); //body is comming as empty object
var phone = request.body.From;
var input = request.body.RecordingUrl;
var twiml = new VoiceResponse();
console.log("phone, input: ", phone, input);
say('What type of podcast would you like to listen. Press any key to finish.', twiml);
twiml.record({
method: 'POST',
action: '/voice/transcribe',
transcribeCallback: '/voice/transcribe',
maxLength: 10
});
respond(response, twiml);
});
app.post("/voice/transcribe", function (request, response, next) {
console.log("request: ", request.body); //body is comming as empty object
var phone = request.body.From;
var input = request.body.RecordingUrl;
var twiml = new VoiceResponse();
var transcript = request.body.TranscriptionText;
console.log("transcribe text: ", transcript);
//here i will do some magic(Ai) to detect user mood and find an
//appropriate mp3 file from my database and send to twilio
var mp3Url = 'https://api.twilio.com/cowbell.mp3'
say('start playing.', twiml);
twiml.play(mp3Url);
respond(response, twiml);
});
app.listen(port, function () {
console.log('app is running on port', port);
});
API Test with postman:
added url as webhook on twilio:
Heroku Logs:
Twilio developer evangelist here.
You are using body-parser which is good. However, you are using the JSON parser. Twilio makes requests in the format of application/www-x-form-urlencoded so you should change:
app.use(bodyParser.json())
to
app.use(bodyParser.urlencoded({ extended: false }))
Then you should see the parsed body as part of the request.body object.
As an extra note, the transcribeCallback is sent asynchronously to the call. So returning TwiML in response to that request won't affect the call at all. You will need to modify the call in flight, by redirecting it to some new TwiML when you get the result of transcription. An example of updating a call with Node.js is below:
const accountSid = 'your_account_sid';
const authToken = 'your_auth_token';
const client = require('twilio')(accountSid, authToken);
client.calls('CAe1644a7eed5088b159577c5802d8be38')
.update({
url: 'http://demo.twilio.com/docs/voice.xml',
method: 'POST',
})
.then((call) => console.log(call.to));

Categories

Resources