Server-Side Deployment using Node.js not giving proper SVG - vega

This is related to question I asked here. One of the solutions was to create a bitmap and I'm trying to do that by exposing a service which returns SVG string from nodejs. I followed doc given here. It's returning a response with SVG content but the svg content doesn't seem to be right.
NodeJS Code
const express = require('express');
const vega = require('vega');
const app = express();
app.get('/vega', (request, response) => {
const spec = JSON.parse(request.query.spec);
const view = new vega.View(vega.parse(spec), {
logLevel: vega.Warn,
renderer: 'none'
});
const svgResult = view.toSVG();
svgResult.then(function(res){
response
.set('Cache-Control', `public, max-age=${60 * 60}`)
.type('svg').send(res);
}).catch((err) => console.log("rejected:", err));
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Listening on ${PORT}`));
Sample call request
http://localhost:3000/vega?spec=%7B%0D%0A++%22description%22%3A+%22A+simple+bar+chart+with+embedded+data.%22%2C%0D%0A++%22data%22%3A+%7B%0D%0A++++%22values%22%3A+%5B%0D%0A++++++%7B%22a%22%3A+%22A%22%2C%22b%22%3A+28%7D%2C+%7B%22a%22%3A+%22B%22%2C%22b%22%3A+55%7D%2C+%7B%22a%22%3A+%22C%22%2C%22b%22%3A+43%7D%2C%0D%0A++++++%7B%22a%22%3A+%22D%22%2C%22b%22%3A+91%7D%2C+%7B%22a%22%3A+%22E%22%2C%22b%22%3A+81%7D%2C+%7B%22a%22%3A+%22F%22%2C%22b%22%3A+53%7D%2C%0D%0A++++++%7B%22a%22%3A+%22G%22%2C%22b%22%3A+19%7D%2C+%7B%22a%22%3A+%22H%22%2C%22b%22%3A+87%7D%2C+%7B%22a%22%3A+%22I%22%2C%22b%22%3A+52%7D%0D%0A++++%5D%0D%0A++%7D%2C%0D%0A++%22mark%22%3A+%22bar%22%2C%0D%0A++%22encoding%22%3A+%7B%0D%0A++++%22x%22%3A+%7B%22field%22%3A+%22a%22%2C+%22type%22%3A+%22ordinal%22%7D%2C%0D%0A++++%22y%22%3A+%7B%22field%22%3A+%22b%22%2C+%22type%22%3A+%22quantitative%22%7D%0D%0A++%7D%0D%0A%7D
Sample response
<svg class="marks" width="0" height="0" viewBox="0 0 0 0" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><g transform="translate(0,0)"><g class="mark-group role-frame root"><g transform="translate(0,0)"><path class="background" d="M0,0h0v0h0Z" style="fill: none;"></path><g></g></g></g></g></svg>
Appreciate any help find what's going wrong here.

Got it working with a few fixes in the above code.
const express = require('express');
const vega = require('vega');
const app = express();
app.get('/vega', (request, response) => {
const spec = JSON.parse(request.query.spec);
getSVG(spec, response);
// let res = render(spec, response);
// console.log('response', res);
});
async function getSVG(spec, response) {
const view = new vega.View(vega.parse(spec), {
loader: vega.loader(),
logLevel: vega.Warn,
renderer: 'none'
})
.initialize()
.finalize();
return (view.toSVG(1))
.then(_ => {
//console.log(_);
console.log("Processed SVG request at -", Date.now());
response
.set('Cache-Control', `public, max-age=${60 * 60}`)
.type('svg').send(_);
});
}
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Listening on ${PORT}`));

Related

getting Can't find / on this server while deploying my app on localhost

when I tried to connect my application with API I'm getting error in my localhost saying
"status": "fail",
"message": "Can't find / on this server",
"error": { statusCode: 404, status: "fail", isOperational: true },
"stack": "Error: Can't find / on this server\n at C:\\Users/*/*app.js:66",
here is my app.js
const express = require("express");
const morgan = require("morgan");
const rateLimit = require("express-rate-limit");
const helmet = require("helmet");
const mongoSanitize = require("express-mongo-sanitize");
const xss = require("xss-clean");
const hpp = require('hpp');
const AppError = require("./API/Utils/appError");
const globalErrorHsndler = require("./API/controllers/errorController");
const usersRouter = require("./API/routes/usersRoute");
const app = express();
app.use(express.json({ limit: "10kb" }));
// DATA SANITIZATION against NoSQL query injection
app.use(mongoSanitize());
// DATA SANITIZATION against site script XSS
app.use(xss());
// PREVENT PARAMETER POPULATION
app.use(
hpp({
whitelist: [
"duration",
"difficulty",
"price",
"maxGroupSize",
"ratingsAverage",
"ratingsQuantity",
],
})
);
// SECURE HEADER HTTP
app.use(helmet());
//RATE LIMIT
const apiLimiter = rateLimit({
windowMs: 60 * 60 * 1000, // 15 minutes
max: 100, // limit each IP to 100 requests per windowMs
message: "Too many requests, please try again later"
});
// apply to specific routes
app.use("/api", apiLimiter);
app.use(morgan("dev"));
//CUSTOM MIDDLE WARE
app.use((req, res, next) => {
console.log("Hey i am from middleware function 👋");
next();
});
app.use((req, res, next) => {
req.requestTime = new Date().toISOString();
next();
});
app.use("/api/v1/users", usersRouter);
//ERROR SECTION
app.all("*", (req, res, next) => {
console.log(`Received request for url: ${req.originalUrl}`);
const error = new AppError(`Can't find ${req.originalUrl} on this server`, 404);
console.log(`Data inside next AppError: ${error}`);
next(error);
});
//GLOBAL ERROR HANDLEING
app.use(globalErrorHsndler);
module.exports = app;
here is my userRouter.js
const express = require("express");
const userControllers = require("./../controllers/userControllers");
const authController = require("./../controllers/authController");
const router = express.Router();
router.post("/signup", authController.signup);
router.post("/login", authController.login);
router.post("/forgotPassword", authController.forgotPassword);
router.patch("/resetPassword/:token", authController.resetPassword);
router.patch("/updateMyPassword", authController.protect, authController.updatePassword);
router.patch("/updateMe", authController.protect, userControllers.updateMe);
router.delete("/deleteMe", authController.protect, userControllers.deleteMe);
//ROUTERS USERS
router
.route("/")
.get(userControllers.getAllUsers)
.post(userControllers.createUser);
router
.route("/:id")
.get(userControllers.getSingleUser)
.patch(userControllers.updateUser)
.delete(userControllers.deleteUser);
module.exports = router;
and here is server.js
const dotenv = require("dotenv");
const mongoose = require("mongoose");
const app = require("./app");
const next = require("next");
const port = process.env.PORT || 3000;
const dev = process.env.NODE_ENV !== "production";
const server = next({ dev });
const handle = server.getRequestHandler();
process.on("uncaughtException", err=>{
console.log("uncaughtException Shutting down Application");
console.log(err.name, err.message);
process.exit(1);
});
dotenv.config({ path: "./config.env" });
const DB = process.env.DATABASE.replace(
"<PASSWORD>",
process.env.DATABASE_PASSWORD
);
mongoose
.connect(DB, {
useCreateIndex: true,
useFindAndModify: false,
useNewUrlParser: true,
})
.then((con) => {
console.log("DB Connection Successfully");
})
server.prepare().then(() => {
app.get("*", (req, res) => {
return handle(req, res);
});
app.listen(port, () => {
console.log(`App running on port ${port}....`);
});
});
process.on("unhandledRejection", (err) => {
console.log("unhandledRejection Shutting down Application");
console.log(err.name, err.message);
server.close(() => {
process.exit(1);
});
});
I need to ask from experts as I'm new to this

Empty body using express post

I can't seem to get the data from this post call. The body shows as an empty object {}.
I've tried several versions including these posts with no luck: Express.js req.body undefined
I've also tried different content-types, but that also hasn't worked.
Thoughts? Thanks in advance.
index.js:
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
const db = require('./queries.js')
const port = 7000
// create application/json parser
var jsonParser = bodyParser.json()
// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })
app.get('/', (req, res) => {
res.json({
info: 'Node.js, Express, and Postgres API'
})
})
app.post('/jothook/', jsonParser, db.jothook)
app.listen(port, () => {
console.log(`App running on port ${port}.`)
})
queries.js:
const Pool = require('pg').Pool
const { req } = require('express');
const pool = new Pool({
user: 'testuser',
host: '167.XX.XX.XX',
database: 'testdb',
password: 'testpwd',
port: 5432,
})
const jothook = (req, res) => {
var qy = JSON.stringify(req.body);
var qy = 'INSERT INTO data_test VALUES ' + qy;
pool.query(qy, (error, results) => {
if (error) {
throw error
}
res.status(201).send(`Data Inserted`)
})
};
module.exports = {
jothook
};
post call:
{headers={Content-Type=application/json}, body="'test_data', 'joe', 'smith'", method=POST, mode=cors}

Socket.io client is not connecting to the server

I am trying to connect to the socket.io client using the following server-side code...
const express = require("express");
const { createServer } = require("HTTP");
const { Server } = require("socket.io");
const app = express();
const httpServer = createServer(app);
const io = new Server(httpServer);
io.on("connection", (socket) => {
console.log("New user connected");
socket.on("join_room", (room) => {
socket.join(room);
socket.on("message", (msg) => {
io.to(room).emit("update_msg", msg);
});
});
});
const PORT = process.env.PORT || 5000;
httpServer.listen(PORT, () => {
console.log(`Server has started on port number ${PORT}`);
});
My client-side code is as follows.
const socket = io("http://localhost:5000");
socket.emit("join_room", "Room1");
When I am running the above codes it does not print anything in the console. I am using socket.io and socket.io-client version 4.5.0 on the server-side and client-side respectively.
const express = require("express");
const { createServer } = require("http");
const { Server } = require("socket.io");
const cors = require('cors')
const app = express();
app.use(cors())
const httpServer = createServer(app);
const io = new Server(httpServer, { cors: {
origin: "http://localhost:4200",
methods: ["GET", "POST"]
}});
io.on("connection", (socket) => {
console.log("New user connected");
socket.on("join_room", (room) => {
socket.join(room);
socket.on("message", (msg) => {
io.to(room).emit("update_msg", msg);
});
});
});
const PORT = process.env.PORT || 5001;
httpServer.listen(PORT, () => {
console.log(`Server has started on port number ${PORT}`);
});
Hope above code will work.
Please confirm, Did you enable the CORS?, if you're trying to access from different origin.
For your'e reference, I have added the CORS while creating the HTTP Server
Ref: https://socket.io/docs/v3/handling-cors/

React native zoomclone app, how to connect different devices via reactapp and able to render other devices streams

how to connect other devices via socketio and webrtc in a react native app. I have tried using API_URL = my pc's ip address || 5000, can anyone tell me how to connect other android devices after installing the react native app. I am done with the coding part, but in node server I am not able to see any user connected, or mediadetails, or roomID or deviceID? I am using nodejs as backend.
I have tried creating peerServer =new Peer(undefined,{host:"/",port:443}) object inside async function.
I am not able to get massage connected client on the server side. i.e
socket.on('connection', () => console.log('connected client')); this line of code is not able to execute correctly.
server.js code
const express = require('express');
const http = require('http');
const socketio = require('socket.io');
const morgan = require('morgan');
const {ExpressPeerServer} = require('peer');
const { join } = require('path');
const app = express();
const server = http.createServer(app)
const io = socketio(server).sockets;
// Borderparser
app.use(express.json());
const customGenerationFunction = () =>
(Math.random().toString(36) + "00000000000000000").substr(2,16);
const peerServer = ExpressPeerServer(server, {
debug: true,
path:'/',
generateClientId: customGenerationFunction,
});
app.use("/mypeer", peerServer);
io.on('connection', function (socket){
socket.on('join-room', ({roomID, userId}) => {
socket.join(roomID);
socket.to(roomID).broadcast.emit("user-connected", userId);
});
});
const port = process.env.PORT || 5000;
server.listen(port, () => console.log(`Server is running on port
${port}`))
--------------------video-action.js codes-------------------------------
import IO from 'socket.io-client';
import Peer from 'react-native-peerjs';
import AsyncStorage from '#react-native-async-storage/async-storage';
import {mediaDevices} from 'react-native-webrtc';
import {ADD_STREAM, MY_STREAM, ADD_REMOTE_STREAM} from './types';
//* api uri*/
export const API_URI = `http://192.168.01.36:5000`;
//**socket config */
export const socket = IO(`${API_URI}`,{
forceNew: true
})
peerServer =new Peer(undefined,
{
host:'192.168.216.202',
secure: false,
port:5000,
path: '/mypeer',
})
peerServer.on('error', console.log);
socket.on('connection', () => console.log('connected client'));
export const joinRoom = (stream) => async (dispatch) => {
const roomID = 'ahdbflarlkhnlfkjvaerbjhfbjds';
//set my own stream
dispatch({type: MY_STREAM, payload: stream});
//open a connection to our server
peerServer.on('open', (userId) => {
socket.emit('join-room', {userId, roomID});
});
socket.on('user-connected', (userId) => {
connectToNewUser(userId, stream, dispatch)
});
// recieve a call
peerServer.on('call', (call) => {
call.answer(stream);
// stream back the call
call.on('stream', (stream) => {
dispatch({type: ADD_STREAM, payload: stream});
});
});
};
function connectToNewUser(userId, stream, dispatch) {
const call = peerServer.call(userId, stream);
}

send serial port data to front-end with express & node

I want to send serial port data to a browser UI with express. So far my code looks like this:
var SerialPort = require("serialport");
var serialport = new SerialPort("/dev/cu.usbmodem1421");
var express = require('express');
var app = express();
var datenFromA;
serialport.on('open', function(){
console.log('Serial Port Opend');
serialport.on('data', function(data){
datenFromA = data[0];
console.log(datenFromA);
});
});
app.get('/', function (req, res) {
res.send('Hello World')
})
app.listen(3000);
Instead of the 'Hello World' I want to send the value of variable datenFromA to the browser. Any ideas how to pass the value to the app.get function?
Thanks in advance.
Essentially you need to wait until you receive an event. Quick dirty example given below:
const SerialPort = require("serialport");
const serialport = new SerialPort("/dev/cu.usbmodem1421");
const express = require('express');
const app = express();
// Only need to do this once.
serialport.on('open', () => console.log('Serial Port Opend'));
app.get('/', async (req, res) => {
const promise = new Promise((resolve, reject) => {
serialport.on('data', (data, err) => {
if (err) {
reject(err);
return;
}
resolve(data[0]);
});
})
const data = await promise;
res.json(data);
})
app.listen(3000);