how do I make my server to to support clients simultaneously when they are fetching my Api in Express?
I am trying to create get request which allow people fetch my api via the get request simultaneously without any error. How am i supposed to do that ?
See also questions close to this topic
-
Make Query With having, count and join in Sequelize
I have two tables in MySQL, joined with a Many to Many relationship. They are as follows:
Equipments:
Field Type Id PK, Integer name Varchar description Varchar createdAt datetime Instructions:
Field Type id FK, integer name Varchar And the table that joins them as a pivot:
EquipmentInstructions:
Field Type equipmentId FK, integer instructionId FK, integer The query I'm trying to do is this, but getting all the fields, not just the name and description.
SELECT P.equipmentId, E.name, E.description FROM EquipmentInstructions P JOIN Equipments E ON P.equipmentId=E.id WHERE P.instructionId IN (1,2,3) GROUP BY P.equipmentId HAVING COUNT(*)=3;
This query returns:
equipmentId, name, description '8', 'ESPATULA', 'Espátula de cocina' '7', 'PARRILLA', 'Para asar la carne' '4', 'CUCHARÓN', 'Cuchara grande'
I am trying to pass said query to Sequelize, so far I have achieved this:
Equipment.findAndCountAll({ include: [ { model: Instruction, as: "instructions", through: { where: { instructionId: { [Op.in]: [1,2,3], }, }, }, attributes: { include: ["id"], }, }, ], group: ["id"], having: Sequelize.where(Sequelize.fn("COUNT", "*"), "=", recipeIds.length), }) .then((result) => { console.log(result); res.json(result); })
The result is correct, however, I only get the id of the equipment:
{ count: [ { id: 4, count: 3 }, { id: 7, count: 3 }, { id: 8, count: 3 } ], rows: [] }
I need to show the complete information of the equipment and additionally count how many records exist in total (by pagination issues).
-
How to ssr Svelte and pass data from express in node js
I am trying svelte and I might use it for my future website, but there is on thing that has stopped me from suing many js frameworks/compilers. It is server side rendering (one reason is I use server-less so it would be easier then prerendering). Is there a way to use express to server-side-render svelte on every request and also pass data from my node js app too so I don't have to make a bunch of other request? For example the App.svelte might be:
<script> export let data let count = 0 </script> <main> <button on:click={count++}>Increase Count BY 1</button> <h1>{data}<h1> </main>
and main.js:
import App from './App.svelte'; const app = new App({ target: document.body, props: { } }); export default app;
I want to get the data value from the server and use it in the svelte code and also sever-side-render it. Is there a way I can do this?
-
how to send long complex array with socket.io?
I have complex an array containing lots of base64 data. and I send this array to server with socket.io. If I send an array containing one or two base64 data. the function is working successfully. but if I send an array containing lots of base64 data. function does not react.
my purpose
- client will prepare templates.
- When the client clicks the save button, it sends this template to the server with socket.io.
- templates sent to the server will be saved to hdd with nodejs.
my array template
const MyArray = [ { div_id:div.id, div_innerhtml:div.innerHTML, //<img src=base64... div_backgroundimage : div.backgroundimage //base64... } ]
client-side code
const MyArray=[],SaveBtn = document.queryselector("#save_div"); const SendArray = (ARRAY)=>{ socket.emit("div_data",ARRAY); } SaveBtn.onclick = ()=>{ SendArray(MyArray); }
server-side code
socket.on("div_data",(data)=>{ console.log(data) // function does not react. let JSON_DATA = JSON.stringify(data) console.log(JSON_DATA) // function does not react. });
Is this socket.io error? What should I do or how should I research this issue?
UPDATE
network tab in devtools
for two base64 image : (function work successfully)
for four base64 image : (function does not react)
-
Parse Multipart Request Body in Node.JS from Flutter Client
I am trying to send along 3 image files to my express server running on Google Cloud Functions.
I am able to get the request to go through, but it is showing up as a buffer on the server.
I am setting fields on the request that I need to grab on the server but am not sure how to parse the
req.body
properly to pull this information off.Future<dynamic> uploadPost(Map<String, dynamic> postData, String placeName, String placeAddress) async { var request = http.MultipartRequest( "POST", Uri.parse('http://localhost:5001/findabite-1ac1a/us-central1/api' + '/posts/add')); request.fields['placeAddress'] = (placeAddress); request.fields['placeName'] = (placeName); request.headers['Content-Type'] = 'application/json'; await Future.forEach(postData.keys, (data) async { final String key = data as String; if (key.startsWith('filePath')) { request.files.add( await http.MultipartFile.fromPath(key, postData[key]), ); } else { request.fields[key] = (postData[key]); } }); request.send(); }
Am I missing something in my client implementation?
This is my express config:
const express = require("express"); const bodyParser = require("body-parser"); const cors = require("cors"); const { routes } = require("./src/routes"); const errorHandler = require("./src/middlewares/error_handler"); var app = express(); app.use( bodyParser.urlencoded({ extended: true, }) ); app.use(bodyParser.json()); app.use(cors({ origin: true })); app.disable("x-powered-by"); app.use(routes); app.use(errorHandler); module.exports = { app };
And this is the output of the console when I try to print
req.body
:<Buffer 2d 2d 64 61 72 74 2d 68 74 74 70 2d 62 6f 75 6e 64 61 72 79 2d 34 68 59 48 5f 65 32 77 31 50 65 48 50 57 5f 31 31 4a 51 48 42 47 5a 39 46 4a 31 34 6b ... 309 more bytes>
-
Accordion Collapsible Does not work only in Heroku (CSP Issue)
Iam facing a very strange issue. I implemented some nested collapsible and also simple collapsible that work excellent at localhost.But in Heroku still i cannot understand why collapsibles do not work. Any help is welcomed, without working collapsible my web app will appear chaotic :(
Pug Layout
doctype html html(lang='en') head title= title meta(charset='utf-8') meta(name='viewport', content='width=device-width, initial-scale=1') script(src="https://code.jquery.com/jquery-3.5.1.slim.min.js", integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj", crossorigin="anonymous") link(rel="stylesheet", href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css", integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z", crossorigin="anonymous") script(src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js", integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV", crossorigin="anonymous") link(rel='stylesheet', href='/stylesheets/style.css') body div(class='container-fluid') div(class='row') div(class='col-sm-2') block sidebar ul(class='sidebar-nav') li a(href='/catalog') Home li a(href='/catalog/resources') All Resources li a(href='/catalog/bookings') My Bookings div(class='col-sm-10') block content
Collapsible PUG
extends layout block content -var i=0; -var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] #accordion.panel-group each doc in object flex-container(style='background-color:#c7e7fa; justify-content:space-around; position:relative;flex-direction:row;margin-left:20px;margin-right:auto; margin-top:20px; width:45%; ') .three(style='text-align:center;margin-left:auto; margin-right:auto; flex: 0 0 40%;') h4='' + doc._id.year + ' ' + months[doc._id.month - 1] -i++; #accordion.panel-group .panel-heading h4.panel-title a.accordion-toggle(data-toggle='collapse', href='#collapses' + i) h6 See Total Cost .panel-collapse.collapse.in(id="collapses" + i) .three(style='width:100%; margin-left:auto; margin-right:auto; flex: 0 0 25%;') h5= 'Total Montly Cost: ' + doc.total_cost_month.toFixed(2) .panel-heading h4.panel-title a.accordion-toggle(data-toggle='collapse', href='#collapse'+i) hr h6 See All Booking details .panel-collapse.collapse.in(id="collapse"+i) each booking in doc.bookings_month flex-container(style='background-color:#a6f1a6; width:100%;') three.flex-container | #[strong Start:] #{moment(booking.date_started).format('DD/MM/YYYY HH:mm')} three.flex-container | #[strong Finish:] #{moment(booking.date_finished).format('DD/MM/YYYY HH:mm')} three.flex-container | #[strong Cost:] #{booking.total_cost.toFixed(2)} li else h1 No booking history found h3= 'Start booking now' + " " a(href='/catalog/resources') | here:
-
Express router app.all('*', (req, res, next)) does not get executed on ec2 instance for HTTP requests. Getting request timed out error
I am running a MEAN stack application. It works fine on my localhost. However, when MEAN stack is deployed on AWS ubuntu server HTTP requests are not getting forwarded to the back-end.
The app.js file looks like:
var app = express(); app.all('*', (req, res, next) => { if (req.secure) { return next(); } else { res.redirect(307, 'https://' + req.hostname + ':' + app.get('secPort') + req.url); } });
On my localhost every HTTP request is entering into if(req.secure) loop and respective routers defined in app.js are getting invoked.
However, when i deploy my MEAN stack application on EC2, the control does not enter into the if condition at all.
I have used NGINX reverse proxy to forward the back-end requests are below:
server { charset utf-8; listen 80 default_server; server_name _; location / { root /opt/front-end; try_files $uri /index.html; } location /* { proxy_pass http://localhost:/3000; } }