I'm trying to generate a code, add it to a database, and then return it to the request server. I'm getting no errors, but the database remains empty, nothing gets added. I'm using glitch as a temporary host, my json file is just {}
My code:
const Discord = require('discord.js')
const rbx = require('noblox.js')
const fs = require("fs")
const express = require("express")
const app = express()
app.use(express.json())
const client = new Discord.Client()
client.verificationCodes = require("./codes.json")
require("dotenv").config()
const port = process.env.PORT
const serverKey = process.env.SERVER_KEY
const cookie = process.env.COOKIE
function randomString(length, chars) {
var result = '';
for (var i = length; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)];
return result;
}
client.on("ready", () => {
console.log("Client is ready.")
})
app.post("/getVerificationCode", function(req,res,next) {
console.log("Recieved")
if (req.body.serverKey !== serverKey) {
console.log("Invalid serverKey supplied.")
return res.status(403).json({
error: "You do not have permission to use this."
})
}
let verificationCode = randomString(4,'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ').toUpperCase()
const userID = parseInt(req.body.userid)
console.log(verificationCode)
client.verificationCodes[userID] = {
code: verificationCode
}
fs.writeFile("./codes.json", JSON.stringify(client.verificationCodes,null,4), err => {
if (err) throw err
})
return res.status(200).json({
VerificationCode: verificationCode
})
})
app.get("/*", function(req,res,next) {
return res.status(200).json({})
})
app.listen(port)
console.log(`App listening on port ${port}`)
function rbxLogin(newCookie) {
try {
rbx.setCookie(newCookie)
} catch(err) {
console.log(`Invalid cookie supplied, or expired. ${err}`)
}
}
// rbxLogin(cookie)
client.login(process.env.BOT_TOKEN)
I watched a video on how to use an fs database. I appreciate any help!
Related
I'm testing the endpoint for /api/sentiment in postman and I'm not sure why I am getting the cannot POST error. I believe I'm passing the correct routes and the server is listening on port 8080. All the other endpoints run with no issue so I'm unsure what is causing the error here.
server.js file
const express = require("express");
const cors = require("cors");
const dbConfig = require("./app/config/db.config");
const app = express();
var corsOptions = {
origin: "http://localhost:8081"
};
app.use(cors(corsOptions));
// parse requests of content-type - application/json
app.use(express.json());
// parse requests of content-type - application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true }));
const db = require("./app/models");
const Role = db.role;
db.mongoose
.connect(`mongodb+srv://tami00:MEUxClWqUNbLz359#cluster0.gmvao.mongodb.net/test?retryWrites=true&w=majority`, {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => {
console.log("Successfully connect to MongoDB.");
initial();
})
.catch(err => {
console.error("Connection error", err);
process.exit();
});
// simple route
app.use('/api/favourite', require('./app/routes/favourite.routes'));
app.use('/api/review', require('./app/routes/review.routes'));
app.use('/api/sentiment', require('./app/routes/sentiment-analysis.routes'));
// routes
// require(".app/routes/favourite.routes")(app);
require("./app/routes/auth.routes")(app);
require("./app/routes/user.routes")(app);
// set port, listen for requests
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}.`);
});
function initial() {
Role.estimatedDocumentCount((err, count) => {
if (!err && count === 0) {
new Role({
name: "user"
}).save(err => {
if (err) {
console.log("error", err);
}
console.log("added 'user' to roles collection");
});
new Role({
name: "creator"
}).save(err => {
if (err) {
console.log("error", err);
}
console.log("added 'creator' to roles collection");
});
new Role({
name: "watcher"
}).save(err => {
if (err) {
console.log("error", err);
}
console.log("added 'watcher' to roles collection");
});
}
});
}
sentiment-analysis routes file
const express = require('express');
const router = express.Router();
const getSentiment = require('../sentiment-analysis/sentimentAnalysis')
router.post('/api/sentiment', (req, res) => {
const data = req.body.data
const sentiment = getSentiment(data)
return res.send({sentiment})
})
module.exports = router;
sentimentAnalysis.js file
const aposToLexForm = require("apos-to-lex-form");
const {WordTokenizer, SentimentAnalyzer, PorterStemmer} = require("natural");
const SpellCorrector = require("spelling-corrector");
const stopword = require("stopword");
const tokenizer = new WordTokenizer();
const spellCorrector = new SpellCorrector();
spellCorrector.loadDictionary();
const analyzer = new SentimentAnalyzer('English', PorterStemmer, 'afinn')
function getSentiment(text){
if(!text.trim()) {
return 0;
}
const lexed = aposToLexForm(text).toLowerCase().replace(/[^a-zA-Z\s]+/g, "");
const tokenized = tokenizer.tokenize(lexed)
const correctSpelling = tokenized.map((word) => spellCorrector.correct(word))
const stopWordsRemoved = stopword.removeStopwords(correctSpelling)
console.log(stopWordsRemoved)
const analyzed = analyzer.getSentiment(stopWordsRemoved);
console.log(analyzed)
}
module.exports = getSentiment;
console.log(getSentiment("Wow this is fantaztic!"))
console.log(getSentiment("let's go together?"))
console.log(getSentiment("this is so bad, I hate it, it sucks!"))
I see that you use your routes like: app.use('/api/sentiment', require('./app/routes/sentiment-analysis.routes'));. But then in your sentiment-analysis you again use /api/sentiment so your request URL should be /api/sentiment/api/sentiment
Shouldn't it be:
const data = req.body.data
Has anybody used fixtures (json file) to load the data in postgres database and execute UI testing ?
Using node-postgres and node-pg-copy-streams can load and remove/delete data from postgres database.
Code and example:
[https://github.com/AmitKulkarni9/fixtures-tests][1]
LoadData.js
const fs = require('fs');
const path = require('path');
const {Client} = require('pg');
const copyFrom = require('pg-copy-streams').from;
const config = require('./config.json');
// Getting connection parameters from config.json
const host = config.host;
const user = config.user;
const pw = config.pw;
const db = config.db;
const port = config.port;
const conString = `postgres://${user}:${pw}#${host}:${port}/${db}`;
class LoadData {
async Load (targetTable) {
try {
const inputFile = path.join(__dirname, `/data/${targetTable}.csv`);
const client = new Client({connectionString: conString,});
client.connect(); // gets connection
const stream = client.query(copyFrom(`COPY ${targetTable} FROM STDIN WITH CSV HEADER`));
const fileStream = fs.createReadStream(inputFile);
fileStream.on('error', (error) =>{
console.log(`Error in creating read stream ${error}`);
client.end();
return;
})
stream.on('error', (error) => {
console.log(`Error in creating stream ${error}`);
client.end();
return;
})
stream.on('finish', () => {
console.log(`Completed loading data into ${targetTable}`);
client.end();
})
fileStream.pipe(stream);
return;
} catch (e) {
console.error(e);
client.end();
return;
}
}
}
module.exports = LoadData;
RemoveData.js
const path = require('path');
const {Client} = require('pg');
const config = require('./config.json');
// Getting connection parameters from config.json
const host = config.host;
const user = config.user;
const pw = config.pw;
const db = config.db;
const port = config.port;
const conString = `postgres://${user}:${pw}#${host}:${port}/${db}`;
class RemoveData {
async Remove (table) {
try {
const client = new Client({connectionString: conString,});
client.connect(); // gets connection
client.query(`DELETE FROM ${table} WHERE id IN ($1,$2,$3) RETURNING *`, [1,2,3], (err, result) => {
if(err) {
console.log(err);
client.end();
return;
} else {
console.log(`Deleted data from ${table}`);
//let results= result.rows;
//console.log(results);
client.end();
return;
}
});
} catch (e) {
console.error(e);
client.end();
return;
}
}
}
module.exports = RemoveData;
I was trying to display a string on the client-side by fetching the result from serverside but for some reason, it is not displaying the fetched data. When I console log the variable straight on the js file the server successfully prints the string. The program is not exporting the variable to the client-side to display it. I can't figure out where I went wrong. Any help is appreciated. Thanks in advance.
const router = require("express").Router();
const {
callName
} = require("pathJs");
router.route("PathRoute").get(async(req, res) => {
const Result = await callName();
return res.json(Result);
});
module.exports = router;
function name() {
const liner = "this works"
console.log(liner)
//updated
return liner;
}
async function callName() {
const data1 = await name()
return data1;
}
callName()
<p id="insertHere" style="color: white;"></p>
<script>
async function caller() {
await fetch(`http://localhost:5000/api/PATH`)
.then((res) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(res.json())
}, 1000)
})
}).then((response) => {
console.log(response)
document.getElementById("insertHere").innerHTML = response.liner
}
)
}
</script>
const express = require("express");
const cors = require("cors");
const routePath = require("./routePath");
const {
response
} = require("express");
require("dotenv").config({
debug: process.env.DEBUG
});
const port = process.env.PORT || 5000;
const app = express();
app.use(cors());
app.use(express.json());
app.use("/api", routePath);
app.listen(port, () => {
console.log(`server is running on port: http://localhost:${port}`);
});
There is no export in pathJs and you want name() to return an object containing liner. You need
function name() {
const liner = "this works"
console.log(liner)
//updated
return {liner};
}
async function callName() {
const data1 = await name()
return data1;
}
callName()
module.exports = { callName };
The backend is probably crashing with TypeError: callName is not a function while handling the request and therefore doesn't send a response.
My /chat route works well through Post method with validation with Joi schema but when I send request through Get method, it show Sending Request and continue loading...
My index.js file:
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const morgan = require('morgan');
const chat = require('./db/ChatModel');
const app = express();
app.use(bodyParser.json());
app.get('/chat', (req, res) => {
chat.getAllMessages().then( (messages) => {
res.json(messages);
});
});
app.post('/chat', (req, res) => {
console.log(req.dody);
chat.createMessages(req.body).then((message) => {
res.json(message);
}).catch( (error) => {
res.status(500);
res.json(error);
});
});
const port = process.env.PORT || 8888;
app.listen(port, () => {
console.log(`Listening on port ${port}...`);
});
In connection.js I coded this
const monk = require('monk');
const connectionString = 'localhost/chatboard';
const db = monk(connectionString);
module.exports = db;
And ChatModal.js has the following code
const Joi = require('joi');
const db = require('./connection');
const schema = Joi.object().keys({
username: Joi.string().alphanum().min(4).max(16).required(),
subject: Joi.string().required(),
message:Joi.string().max(300).required(),
imgUrl: Joi.string().uri({
scheme: [ // https://github.com/hapijs/joi/blob/v14.3.1/API.md#stringurioptions
/https?/
]
})
});
const chat = db.get('chat');
function getAllMessages() {
return chat.find();
};
function createMessages(message) {
const result = Joi.validate(message, schema);
if (result.error == null) {
message.created = new Date();
return chat.insert(message);
} else {
return Promise.reject(result.error);
}
}
module.exports = {
createMessages,
getAllMessages
};
I can't understand why getAllMessages() doesn't work and postman continue loading when Get request applied like this http://prntscr.com/s0d9c5
ChatModal.js
function getAllMessages() {
try {
return chat.find();
} catch (err) {
return next(err);
}
index.js
app.get('/chat', (req, res, next) => {
try{
data = chat.getAllMessages()
} catch (err) {
return next(error);
}
res.json(data);
});
User try-catch in the ChatModal.js and also index.js then you can understand what is actual error, like bellow:
ChatModal.js
function getAllMessages() {
try {
chat.find();
} catch (err) {
return next(err);
}
I think, may be your data, i mean message list data so weight, in this case you get all message,res.json(messages); json method have long time to parse messages data
I'm testing a React app with an Express backend, using Jest and Supertest. In my current test, I need to stub the fetch, which I'm doing with Supertest. The problem is, I never get an answer from the agent get(), and thus never get any data back.
I think there is a problem with how I'm exporting my server. I've tried changing around the exports, from module.exports = app, to module.exports = {app}, to const server = app.listen(port, etc), and module.exports = server. So far none of the solutions I've found are working.
server.js:
const app = require('./app.js');
const port = process.env.PORT || 8080;
app.listen(port, () => console.log("Server running on port " + port));
app.js:
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const app = express();
const ews = require('express-ws')(app);
const WebSocket = require('ws');
...
app.get("/menus", (req, res) => {
const menus = MenuRepo.getMenus();
res.json(menus)
})
...
module.exports = app;
home-test.js
test("Test that dishes displays", async () => {
menuRepo.populateMenus();
overrideFetch(app);
const driver = mount(
<MemoryRouter>
<ShowMenus/>
</MemoryRouter>
);
const predicate = () => {
driver.update();
const tableSearch = driver.find('#menuTable');
const tableIsDisplayed = (tableSearch.length >= 1);
return tableIsDisplayed;
};
const displayedTable = await asyncCheckCondition(predicate, 3000, 200);
expect(displayedTable).toBe(true);
const menus = menuRepo.getMenus();
const html = driver.html();
for(let i=0; i<menus.length; i++){
expect(html).toContain(menus[i].dishes.day);
}
});
function I'm using to stub fetch:
function overrideFetch(app){
const agent = request.agent(app);
global.fetch = async (url, init) => {
let response;
if(!init || !init.method || init.method.toUpperCase() === "GET"){
try {
response = await agent.get(url);
} catch (e) {
console.log(e)
}
} else if(init.method.toUpperCase() === "POST"){
response = await agent.post(url)
.send(init.body)
.set('Content-Type', init.headers ? init.headers['Content-Type'] : "application/json");
} else if(init.method.toUpperCase() === "PUT"){
response = await agent.put(url)
.send(init.body)
.set('Content-Type', init.headers ? init.headers['Content-Type'] : "application/json");
} else if(init.method.toUpperCase() === "DELETE"){
response = await agent.delete(url);
} else {
throw "Unhandled HTTP method: " + init.method;
}
const payload = response.body;
return new Promise( (resolve, reject) => {
const httpResponse = {
status: response.statusCode,
json: () => {return new Promise(
(res, rej) => {res(payload);}
)}
};
resolve(httpResponse);
});
};
}
I'm expecting that the stubbed fetch will return a list of seven json menus.