Categories
JavaScript Answers

How to add basic Ajax send/receive with Node.js?

To add basic Ajax send/receive with Node.js, we can use Express and fetch.

For instance, we write

const app = require("express").createServer();

app.get("/string", (req, res) => {
  const strings = ["foo", "bar", "baz"];
  const n = Math.floor(Math.random() * strings.length);
  res.send(strings[n]);
});
app.listen(8001);

to add the get /string route which returns a random string from the strings array as the response body with res.send.

Then we write

const res = await fetch("/string");
const string = await res.text();

to make a get request to /string with fetch.

And get the response body with res.text.

Categories
JavaScript Answers

How to fix Cordova Unable to load platformapi with JavaScript?

To fix Cordova Unable to load platformapi with JavaScript, we remove the platforms.

To do this, we run

ionic cordova platform rm browser/android/ios

to remove the platforms with platform rm.

Then we run

ionic cordova run --emulator

to run the emulator.

Categories
JavaScript Answers

How to fix TypeError: Request path contains unescaped characters error with Node?

To fix TypeError: Request path contains unescaped characters error with Node, we call the encodeURI function.

For instance, we write

const uri = "my test.asp?name=ståle&car=saab";
const res = encodeURI(uri);

to call encodeURI to return an escaped version of the uri string.

Categories
JavaScript Answers

How to fix Cannot find module for a Node app running in a Docker compose environment?

To fix Cannot find module for a Node app running in a Docker compose environment, we’ve to install the dependencies.

To do this, we write

FROM node:boron

# Create app directory
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app

# Install app dependencies
COPY package.json /usr/src/app/
RUN npm install

# Bundle app source
COPY . /usr/src/app

EXPOSE 8080
CMD [ "npm", "start" ]

to run npm install with RUN npm install to install the dependencies in our Dockerfile.

Categories
JavaScript Answers

How to send flash messages in Node Express 4.0?

To send flash messages in Node Express 4.0, we use the flash package.

To add it, we write

app.use(flash());

Then we send a flash message in our middleware with

req.flash("signupMessage", anyValue);

The first argument is the key and the 2nd is the value.