How to Connect Back4app Database with Nodejs And Express.
Step 1: Install node JS using the following command
npm init -y
Step 2: For connectivity, you need Express JS. You can install this as given below -
npm install express
Step 3: For back4app connectivity, you must have a parse server.
Install parse as follows -
npm install parse/node
{
"name": "demo",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.1",
"parse": "^3.1.0"
}
}
Step 4: Take appId and javascript Id from back4app account
You will get this id in the back4app console. Also, create a class on the back4app.
I have created class name Apartment which includes columns as below:-
name: String
address: String
Step 5: Create index.js file in root directory write below code in index.js.
const Parse = require("parse/node");
const express = require("express");
const app = express();
const APP_ID = "rPrUuCQt2OigJga1QGHj4ElzPIyx4zridlBiuTDz";
const JAVASCRIPT_KEY = "ooNnCYY3ynkTtGXdRL31M19y2tDc1oJdLOyB3hby";
console.info("Initializing Application", APP_ID);
Parse.initialize(APP_ID, JAVASCRIPT_KEY);
Parse.serverURL = "https://parseapi.back4app.com/";
const Appartment = Parse.Object.extend("Appartment");
const appartment = new Appartment();
const appartmentQuery = new Parse.Query(Appartment);
// create();
app.post("/", (req, res) => {
const rockEvent = {
name: "Rock n Rio",
address: "originating in Rio de Janeiro.",
};
appartment
.save(rockEvent)
.then((obj) => obj.toJSON())
.then((event) => {
console.log("Object saved:\n", event);
})
.catch(console.error);
});
Fetch data from database using API
app.get("/", (req, res) => {
appartmentQuery
.find()
.then((obj) => {
res.json(obj);
})
.catch(console.error);
});
To Delete data from the database using API
app.delete("/", (req, res) => {
appartmentQuery.first("ObjectId").then((eventToDelete) => {
if (eventToDelete !== undefined) {
eventToDelete
.destroy()
.then((eventDeleted) => {
res.json(eventDeleted.id);
})
.catch(console.error);
}
});
});
You must mention which port you are working on.
const port = process.env.PORT || 4000;
app.listen(4000, () => {
console.log(`Server is running on port ${port}.`);
});
Step 6: Now open a terminal and go to your directory then run your node project using
below command.
node index.js
Comments
Post a Comment