request.body is giving me empty brackets or undefined - javascript

I am using body parsing middleware. I have installed the body-parser library. it seems as though I have tried everything but nothing is working.
here's my server code.
const express = require('express');
const app = express();
const bp = require('body-parser');
app.use(bp.json())
app.use(bp.urlencoded({ extended: true }))
app.use(express.static('/Users/anthonyquesen/Desktop/webzite/drive-download-20201123T191109Z-001/public'))
app.post('/api', async(req,res) => {
console.log(req.body.firstName);
res.json({status: 'ok'})
});
app.listen(3000, () =>{
console.log('server listening at 3000')
});
here's my client-side javascript code:
let charCreate = function(cCreator){
let lastName = "name"
let firstName= "reggy"
let cCreatorX = cCreator.windowWidth/1.6;
let charWindow;
let clickedCreator;
let bagClicked;
let dreamJournalClicked;
cCreator.setup = function()
{
cCreator.cCreatorCanvas = cCreator.createCanvas(cCreatorX-200,cCreatorX-200);
cCan = document.getElementById('charCreate');
cCreator.cCreatorCanvas.parent(cCan);
charWindow = characterCreate;
clickedCreator = false;
bagClicked = false;
dreamJournalClicked = false;
};
cCreator.draw = function()
{
cCreator.clear();
// cCreator.background(255,50)
cCreator.image(charWindow,0,-130,cCreatorX-200,cCreatorX);
if (cCreator.mouseX>cCreatorX/2-170 && cCreator.mouseX<cCreatorX/2 && cCreator.mouseY>cCreatorX/11-22 && cCreator.mouseY<cCreatorX/11-22+190 || bagClicked)
{
cCreator.image(seedBagOnHover,cCreatorX/2-170,cCreatorX/11-22,170,190);
}
else
{
cCreator.image(seedBag,cCreatorX/2-170,cCreatorX/11-22,170,190);
};
cCreator.image(dreamJournal,cCreatorX/2+10,cCreatorX/11+80,111,123);
};
cCreator.mouseClicked = function()
{
clickedCreator = true;
if (cCreator.mouseX>cCreatorX/2-170 && cCreator.mouseX<cCreatorX/2 && cCreator.mouseY>cCreatorX/11-22 && cCreator.mouseY<cCreatorX/11-22+190 && clickedCreator)
{
charWindow = gardenWreath;
bagClicked = true;
seedBagSound.play();
/** API request **/
fetch('/api', {
headers: {'Content-Type' : 'applications/json'},
method: "POST",
body: JSON.stringify({firstName,
lastName,
})
});
/** **/
console.log(JSON.stringify({firstName,lastName}));
};
};
if (cCreator.mouseX>cCreatorX/2+10 && cCreator.mouseX<cCreatorX/2+10+111 && cCreator.mouseY>cCreatorX/11+80 && cCreator.mouseY<cCreatorX/11+80+123)
{
charWindow = dreamerWreath;
dreamjournalClicked = true;
};
};
let cCreate = new p5(charCreate);
The entire function here is the name spaced/ in instance mode because I'm also using p5.js SDK If that has something to do with the code not working as well. there is a Lil more to the code of the client-side like a function that runs cCreator in p5 and other stuff but the main point is the fetch is not sending the code to the terminal. whenever I click the button it sends the post. It knows something sent it just comes back in the terminal as undefined. I'm hoping someone can take a look at this
thank you so much!

Related

Javascript working in Chrome, working in firefox locally, but not after deployment

This is part of a Spark Java app, but the error is happening in this JS part. The relevant code is as follows:
const addErrBox = async () => {
const controls = document.querySelector(".pure-controls");
const errBox = document.createElement("p");
errBox.setAttribute("id", "errBox");
errBox.setAttribute("style", "color:red");
errBox.innerHTML = "Short URL not valid or already in use!";
controls.appendChild(errBox);
}
const submitForm = () => {
const form = document.forms.namedItem("new-url-form");
const longUrl = form.elements["longUrl"];
const shortUrl = form.elements["shortUrl"];
const url = `/api/new`;
fetch(url, {
method: "POST",
body: `${longUrl.value};${shortUrl.value}`
})
.then((res) => {
if (!res.ok) {
if (document.getElementById("errBox") == null) {
addErrBox();
}
}
else {
document.getElementById("errBox")?.remove();
longUrl.value = "";
shortUrl.value = "";
refreshData();
}
});
};
(async () => {
await refreshData();
const form = document.forms.namedItem("new-url-form");
form.onsubmit = e => {
e.preventDefault();
submitForm();
}
})();
Basically, "/api/new" checks for validity of input, adds the data to database if valid and prints error otherwise. Now, when the input is valid, it seems to work. The "/api/new" code is in Java, which seems to work properly as well since I do get a 400 error. All of it works properly when built inside a docker locally, but when accessed over internet using Nginx reverse proxy, it stops working inside firefox. Chrome still works. I'm not sure what's happening.
The code for "/api/new" is this:
public static String addUrl(Request req, Response res) {
var body = req.body();
if (body.endsWith(";")) {
body = body + "$";
}
var split = body.split(";");
String longUrl = split[0];
if (split[1].equals("$")) {
split[1] = Utils.randomString();
}
String shortUrl = split[1];
shortUrl = shortUrl.toLowerCase();
var shortUrlPresent = urlRepository
.findForShortUrl(shortUrl);
if (shortUrlPresent.isEmpty() && Utils.validate(shortUrl)) {
return urlRepository.addUrl(longUrl, shortUrl);
} else {
res.status(HttpStatus.BAD_REQUEST_400);
return "shortUrl not valid or already in use";
}
}
Update: it suddenly started working, without any change on the server side. I think it was some kind of issue with caching, either in firefox, cloudflare or Nginx's part.

Writing data to JSON file using nodeJS takes too long

i am creating a function that Count the clicks of elements , and put them in JSON file
const fs = require('fs');
const file = fs.readFileSync('public/js/count.json');
const Words = JSON.parse(file);
const express = require('express');
const app = express();
app.listen(process.env.PORT || 3000, () => console.log('we are listeining'));
app.use(express.static('public'));
app.use(express.json({ limit : '1mb' }));
app.get('/add/:word', addWord);
function addWord(request, response) {
var data = request.params;
var word = data.word;
var reply;
var found = false;
for (i = 0; i < Words.length; i++){
if (Words[i].type == word){
Words[i].count++;
found = true;
break;
}
}
if (!found) {
Words.push({"type": word , "count": 1});
}
var x = JSON.stringify(Words, null, 2);
fs.writeFile('public/js/count.json', x, finished);
function finished(){
console.log('Yay')
}
/*
console.log(Words[word]); */
/* response.send(reply); */
}
when i run the code through my script
async function counter(elemid){
let response = await fetch("/add/"+elemid);
}
it takes too long to respond , and sometimes it gives request timeout , is there is a faster way to do the exact same purpose
You are not writing a response in your finished handler. This is leaving each request to only end via timeout.
In your finished function add response.end() at the end.
You can verify that this is working by ensuring that the request receives a 200 response from your server instead of timing out.

How can I call a restapi function from frontend (ejs/html) [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 3 years ago.
I am trying to basically call the 'get' method from html/ejs when a button is pressed to query the database and display the results. Sorry if it's very simple, but I just can't get it work.
I tried to require the file and call the function inside a script tag but that doesn't work on the browser. I tried to add the js file with a <script src="text/javascript" src="filename"> but that also results in errors.
The rest API I built talks to oracle 11g (Toad) using oracledb.
I am basically trying to call the get function in this class
const employees = require('../db_apis/employees.js');
async function get(req, res, next) {
try {
const context = {};
context.id = parseInt(req.params.id, 10);
const rows = await employees.find(context);
if (req.params.id) {
if (rows.length === 1) {
res.status(200).json(rows[0]);
} else {
res.status(404).end();
}
} else {
res.status(200).json(rows);
}
} catch (err) {
next(err);
}
}
...
db_apis/employees.js
const oracledb = require('oracledb');
const database = require('../services/database');
async function find(context) {
const baseQuery =
`SELECT *
FROM choice_names`;
console.log('in find');
let query = baseQuery;
const binds = {};
let additionalQuery = '\nwhere ';
if (context.id) {
binds.choice_name = context.id;
additionalQuery += `choice_name = :choice_name`;
// query += `\nwhere choice_name = :choice_name`;
} else if (context.user) {
binds.choice_user = context.user;
additionalQuery += `choice_user = :choice_user`;
} else if (context.date) {
binds.choice_date = context.date;
additionalQuery += `choice_date = :choice_date`;
}
if (context.id || context.user || context.date) {
query += additionalQuery;
}
console.log(query);
const result = await database.simpleExecute(query, binds);
return result.rows;
}
...
router.js
const express = require('express');
const router = new express.Router();
const employees = require('../controllers/employees');
router.route('/employees/:id?')
.get(employees.get)
.post(employees.post)
.put(employees.put)
.delete(employees.delete);
module.exports = router;
index.ejs
...
<button onclick="get()">Click me</button>
...
You are (very)confusing frontend and backend code.
The express app is in backend, running on some port, exposing the /employees/:id route.
But the frontend part doesn't have access to the backend scripts, So you need to do a XHR(Ajax) request from frontend to that route and get the result.
For example, in jQuery it can be something as
function get(){
$.get('/employees/1').done(..do something..)
}
You can refer this answer on how to do it on angular.

How do I connect to a Clover mini device using ONLY node?

I'm fairly new to Node, and I'm trying to connect to a Clover Mini device through a websocket using the API provided by Clover.
I've tried modifying the example code below to work using only node, but when I open it in node nothing happens. (No errors, just nothing happens at all)
It works in Chrome just fine, so what's missing?
https://github.com/clover/remote-pay-cloud
var $ = require('jQuery');
var clover = require("remote-pay-cloud");
var log = clover.Logger.create();
var connector = new clover.CloverConnectorFactory().createICloverConnector({
"oauthToken": "1e7a9007-141a-293d-f41d-f603f0842139",
"merchantId": "BBFF8NBCXEMDV",
"clientId": "3RPTN642FHXTX",
"remoteApplicationId": "com.yourname.yourapplication:1.0.0-beta1",
"deviceSerialId": "C031UQ52340015",
"domain": "https://sandbox.dev.clover.com/"
});
var ExampleCloverConnectorListener = function(cloverConnector) {
clover.remotepay.ICloverConnectorListener.call(this);
this.cloverConnector = cloverConnector;
};
ExampleCloverConnectorListener.prototype = Object.create(clover.remotepay.ICloverConnectorListener.prototype);
ExampleCloverConnectorListener.prototype.constructor = ExampleCloverConnectorListener;
ExampleCloverConnectorListener.prototype.onReady = function (merchantInfo) {
var saleRequest = new clover.remotepay.SaleRequest();
saleRequest.setExternalId(clover.CloverID.getNewId());
saleRequest.setAmount(10000);
this.cloverConnector.sale(saleRequest);
};
ExampleCloverConnectorListener.prototype.onVerifySignatureRequest = function (request) {
log.info(request);
this.cloverConnector.acceptSignature(request);
};
ExampleCloverConnectorListener.prototype.onConfirmPaymentRequest = function (request) {
this.cloverConnector.acceptPayment(request.payment);
};
ExampleCloverConnectorListener.prototype.onSaleResponse = function (response) {
log.info(response);
connector.dispose();
if(!response.getIsSale()) {
console.error("Response is not an sale!");
console.error(response);
}
};
var connectorListener = new ExampleCloverConnectorListener(connector);
connector.addCloverConnectorListener(connectorListener);
connector.initializeConnection();
After getting into contact with the developers at clover, their documentation had some errors. For other users sake here is the link to that issue on their gitub as well as some example code.
link to github issue
const endpoint = "ws://yourip:yourport/remote_pay";
var webSocketFactory = function () {
let webSocketOverrides = {
createWebSocket: function () {
// To support self-signed certificates you must pass rejectUnauthorized = false.
// https://github.com/websockets/ws/blob/master/examples/ssl.js
let sslOptions = {
rejectUnauthorized: false
};
// Use the ws library by default.
return new WebSocket(endpoint, sslOptions);
}
}
return Object.assign(new clover.CloverWebSocketInterface(endpoint), webSocketOverrides);
};
var ExampleWebsocketPairedCloverDeviceConfiguration = function () {
clover.WebSocketPairedCloverDeviceConfiguration.call(this,
endpoint, // endpoint
"com.cloverconnector.javascript.simple.sample:1.4", // Application Id
"Javascript Simple Sample", // posName
"Register_1", // serialNumber
null, // authToken().get(
webSocketFactory,
new clover.ImageUtil());
};

How to invoke JS function from one file to another in node.js?

I am new to JS and trying to break the code into multiple modules. I am running nodejs and I am puzzled here on why is it complaining about
pathChecker not defined. Any ideas on it?
<
const http = require('http');
const parseUrl = require('parseurl');
const path = require('path');
http.createServer( function (req, res)
{
try
{
// this is library function
var pathName = decodeURIComponent(parseUrl(req));
// create a literal validateFile to validate the path
var validateFile = new pathChecker(pathName);
// This is an engine to validate the path problems related to security, existence etc.
validateFile.pathCheck();
if(validateFile.error === true) {
res.statusCode = validateFile.statusCode;
res.end(validateFile.ErrorMsg);
return;
}
}
catch(err)
{
res.statusCode = err.status || 500;
res.end(err.message);
}
}).listen(4000);
I have another file called
errorHandler.js
function pathChecker(path)
{
this.error = true;
this.path = path;
this.statusCode = 500;
this.ErrorMsg = "Internal Server Error";
this.pathCheck = function()
{
if(!path)
{
this.statusCode = 400;
this.ErrorMsg = 'path required';
this.error = true;
}
else{
this.statusCode = 200;
this.ErrorMsg = undefined;
this.error = false;
}
}
};
On running this, I get the output
pathChecker is not defined
You need to export and import the file as a module. You do this like this:
// File A.js
function A() {
}
module.exports = A;
// File B.js
var A = require("./A");
A();
Note that the name A is arbitrary on the import and you can name whatever you want. You can also export an object with functions on it instead of a single function and then when importing you can get properties off of it. This way you can export more than one function or value from a single file.
You need to export the function in your errorHandler.js file.
function pathChecker(path) {
...
}
module.exports = pathChecker;
then import it into your main file with
const pathChecker = require("./errorHandler")

Categories

Resources