I'm using MEAN stack as my back-end. this is my server js file
const users = require('./routes/users');
app.get('/', (req, res) => {
res.send('Invalid endpoint');
});
This is my routes file users.js
router.get('/jobdetail', function(req,res) {
console.log('fetching jobs');
jobDetails.find({}, (err,jobs) => {
if(err) {
console.log(err);
}
else {
res.json(jobs);
}
});
});
when I run it the postman bu url:
localhost:3000/api/jobdetail
Instead of the data from MongoDB I get the response as
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
<script type="text/javascript" src="http://gc.kis.v2.scr.kaspersky-labs.com/D11634C0-514E-C94E-9DFD-54EBD0B16E5F/main.js" charset="UTF-8"></script>
</head>
<body>
<pre>Cannot GET /api/jobdetail</pre>
</body>
</html>
var api = require('../routes/users.js');
app.use('/api', api);
in your routes/users.js file :
var mongoose =require('mongoose');
var router = require('express').Router();
var conn = mongoose.connection;
conn.once("open", () => {
router.get('/jobdetail', function(req, res) {
jobDetails.find({}, (err,jobs) => {
if(err) {
console.log(err);
}
else {
res.json(jobs);
}
});
});
});
module.exports = router;
Related
I am trying through node js, express and mongoose to create a way to add the same mongoose Schema more than one time I want to use a trigger button. I have to restart the server to add more to the DB.
Later on I want to change it through a counter but first I need to get this working.
I am trying to solve it on my own but I got stuck, thank you for your help !
the app.js I use as server.
/app.js
const express = require('express');
const { default: mongoose } = require('mongoose');
const path = require('path');
const db = require("./database");
const app = express();
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
app.use(express.static('DB'));
app.use('/Dev', express.static(path.join(__dirname, 'Dev', 'public')));
//Export function to new a .js file
var ClickyClicky = new mongoose.Schema({
name: {
type: String,
require: true
}},
{
timestamps: true, //time
}
);
var Clicky = mongoose.model('Click', ClickyClicky, 'clickystore');
var Clicks = new Clicky({ name: 'Test' });
//Export function to new a .js file
//Save button trigger.
app.post('/test', (req, res) => {
Clicks.save(function (err, book) {
if (err) return console.error(err);
console.log(book.name + " saved to bookstore collection.");
});
});
//Save button trigger.
app.post('/alfa', (req, res) => {
Clicks.save(function (err, name) {
if (err) return console.error(err);
console.log(name.name + " saved to name collection.");
});
});
// // 404 page
app.all('*', (req, res) => {
res.status(404).send('<h1>404, Page not found !</h1>');
});
app.listen(5000, () => {
console.log('Server started at http://localhost:5000');
});
/client.js
console.log('Client code running');
const testButton = document.getElementById('Button');
testButton.addEventListener('click', function(e) {
console.log('Butten was clicked');
fetch('/test', {method: 'POST'})
.then(function(response) {
if(response.ok) {
console.log('Click was recorded');
return;
}
throw new Error('Request failed.');
})
.catch(function(error) {
console.log(error);
});
});
const testButton2 = document.getElementById('Button2');
testButton2.addEventListener('click', function(e) {
console.log('Butten was clicked');
fetch('/alfa', {method: 'POST'})
.then(function(response) {
if(response.ok) {
console.log('Click was recorded');
return;
}
throw new Error('Request failed.');
})
.catch(function(error) {
console.log(error);
});
});
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button id="Button">Click me for a test!</button>
<button id="Button2">Click me for a test1!</button>
</body>
<script src="./Dev/Client.js"></script>
</html>
\database.js
require('dotenv').config();
const mongoose = require('mongoose');
mongoose.set("strictQuery", false);
mongoose.connect(process.env.MONGOOB_URI, () => {
console.log("Connected to MongoDB");
});
I solved my issue with adding, unique: false to my mongoose schema and deleted the old input from the BD
i am testing this url==> (http://localhost:8800/api/users/634ed4af41fb0169e999deb2/follow) on
postman, it works in case of without having (/follow), But when i use this url every time i get this error=====>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot PUT /api/users/634ed4af41fb0169e999deb2/follow%0A</pre>
</body>
</html>
Below i am getting issue in using // app.use('/api/users',userRoutes)//. This will call the router present in the users.js
index.js
const express= require("express");
const app=express();
const mongoose=require("mongoose");
const dotenv=require("dotenv");
const helmet=require("helmet");
const morgan=require("morgan");
const userRoutes=require("./routes/users")
const authRoutes=require("./routes/auth");
dotenv.config();
mongoose.connect(process.env.MONGO_URL,
{useNewUrlParser: true, useUnifiedTopology: true}, ()=>{
console.log("connected to database");
});
//middleware
app.use(express.json());
app.use(helmet());
app.use(morgan("common"));
//cutom middleware for Routing
app.use('/api/users',userRoutes);
app.use('/api/auth',authRoutes);
app.listen(8800,()=>{
console.log("backend server running");
})
here in user.js controller are not able to log the console present at the top position.
user.js
const router=require("express").Router();
const bcrypt=require('bcrypt');
const User = require("../models/User");
//follow user
router.put("/:id/follow", async (req , res)=>{
console.log(req.body.userId === req.params.id.trim());
if(req.body.userId !== req.params.id){
try {
const user= await User.findById(req.params.id);
const currentUser= await User.findById(req.body.userId);
if(!user.followers.includes(req.body.userId)){
await user.updateOne({$push:{followers:req.body.userId}});
await currentUser.updateOne({$push:{followings:req.params.id}});
res.status(200).json("user has been follwed")
}else{
res.status(403).json('you all ready followed')
}
} catch (error) {
res.status(500).json(error)
}
}
else{
res.status(403).json("you cant follow yourself")
}
})
My index.js file on root directory
const express = require("express");
const app = express();
const path = require("path");
const axios = require("axios").default;
const cors = require("cors");
app.set("view engine", "ejs");
app.set("views", path.join(__dirname, "/views"));
app.use(
cors({
origin: "http://localhost:3000",
})
);
fetchData = async () => {
const data = await axios.get(
"https://nepse-data-api.herokuapp.com/data/todaysprice"
);
console.log(data);
return data;
};
app.get("/", (req, res) => {
const nepseData = fetchData();
res.render("home.ejs", { nepseData });
});
app.listen(3000, () => {
console.log("listening to port 3000");
});
My home.ejs file on views directory
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<%= nepseData %>
</body>
</html>
The browser is displaying this when I run the server
The API is sending this type of data
I want to show the name and prices on my ejs file. What should I do now??
You have to add await there:
app.get("/", async (req, res) => {
const nepseData = await fetchData();
res.render("home.ejs", { nepseData });
});
And then you can iterate over the data:
<% nepseData.forEach(function(row){ %>
<%= row.companyName %> <%= row.minPrice %>
<% }); %>
I'm fairly new to Nodejs and I'm building an app that ssh to a remote machine and get a tail -f of a log file.
The lines of the log file I'm receiving I'm sending to the client via socket-io (ver. 2.0.3)
Now I'm facing a problem that when a second browser tries to tail a different log, the new log is sent to both of the browsers instead of only the one who made the request.
I'm not sure if it's a problem with my socket-io code or the child_process.
Here's the server:
const express = require('express'),
app = express(),
path = require('path'),
bodyParser = require('body-parser'),
logger = require('morgan'),
server = require('http').Server(app),
io = require('socket.io')(server),
spawn = require('child_process').spawn,
events = require('events'),
eventEmitter = new events.EventEmitter();
// Fix body of requests
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
// Log the requests
app.use(logger('dev'));
// Serve static files
app.use(express.static(path.join(__dirname, '.')));
// Add a basic route – index page
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname, 'index.html'));
});
io.on('connection', (socket) => {
console.log(`client connected ${socket.client.id}`);
eventEmitter.on('tail', (data) => {
socket.tail = spawn('ssh', ['root#' + 'quality-p.company.com', 'tail -f', data.service], { shell: true });
socket.tail.stdout.on('data', (data) => {
console.log(`got new data ${data.toString()}`);
socket.emit('newLine', {line: data.toString().replace(/\n/g, '<br />')});
});
});
});
app.get('/tail', (req, res) => {
eventEmitter.emit('tail', req.query);
res.sendStatus(200);
});
// Bind to a port
server.listen(3005, () => {
console.log('running on localhost:' + 3005);
});
Client:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="./node_modules/socket.io-client/dist/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
$(() => {
let socket = io();
socket.on('connect', () => {
console.log('connected');
});
socket.on('newLine', (data) => {
console.log(`new data: ${data.line}`);
$("#tailing").append(data.line);
});
$('#tail').click(() => {
$.get('/tail', {
service: $('#service').val()
});
});
});
</script>
<title>Title</title>
</head>
<body>
<select id="service">
<option id="tnet" value="/var/log/tnet">tnet</option>
<option id="consul" value="/var/log/consul">consul</option>
</select>
<button id="tail">tail</button>
<div id="tailing" style="background-color: antiquewhite;">
</div>
</body>
</html>
Server
const express = require('express'),
app = express(),
path = require('path'),
bodyParser = require('body-parser'),
logger = require('morgan'),
server = require('http').Server(app),
io = require('socket.io')(server),
spawn = require('child_process').spawn;
// Fix body of requests
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
// Log the requests
app.use(logger('dev'));
// Serve static files
app.use(express.static(path.join(__dirname, '.')));
// Add a basic route – index page
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname, 'index.html'));
});
var tails = {};
io.on('connection', (socket) => {
console.log(`client connected ${socket.client.id}`);
socket.on('tail', (data) => {
socket.join(data.service);
if (typeof tails[data.service] == "undefined") {
tails[data.service] = spawn('ssh', ['root#' + 'quality-p.company.com', 'tail -f', data.service], {
shell: true
});
tails[data.service].stdout.on('data', (data) => {
console.log(`got new data ${data.toString()}`);
io.to(data.service).emit('newLine', {
line: data.toString().replace(/\n/g, '<br />')
});
});
}
});
});
// Bind to a port
server.listen(3005, () => {
console.log('running on localhost:' + 3005);
});
Client
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="./node_modules/socket.io-client/dist/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
$(() => {
let socket = io();
socket.on('connect', () => {
console.log('connected');
});
socket.on('newLine', (data) => {
console.log(`new data: ${data.line}`);
$("#tailing").append(data.line);
});
$('#tail').click(() => {
socket.emit('tail', {
service: $('#service').val()
});
});
});
</script>
<title>Title</title>
</head>
<body>
<select id="service">
<option id="tnet" value="/var/log/tnet">tnet</option>
<option id="consul" value="/var/log/consul">consul</option>
</select>
<button id="tail">tail</button>
<div id="tailing" style="background-color: antiquewhite;">
</div>
</body>
</html>
Here is my sample code:
File: index.js
var express = required('express');
var app = express();
app.get("/", function(req, res){
...
...
res.render("/index", {
list: data
});
});
File: test.js
var chai = require('chai');
var chaiHttp = require('chai-http');
var server = require('../index');
var should = chai.should();
chai.use(chaiHttp);
describe('Homepage', function(done){
it('should render index view', function(done){
chai.request(server.app)
.get("/")
.end(function(err, res){
console.log(res.body);
});
});
});
The console.log(res.body) shows output as {}. How can I get the local list variable to show in the output? I want to test if this local list variable has any data in my test.js file.
Option 1. You should use res.json([body]) to send the list data to your test case.
E.g.
index.js:
var express = require('express');
var app = express();
app.get('/', function (req, res) {
const data = ['a', 'b'];
res.json({ list: data });
});
module.exports = { app };
index.test.js:
var chai = require('chai');
var chaiHttp = require('chai-http');
var server = require('./index');
var should = chai.should();
chai.use(chaiHttp);
describe('Homepage', function (done) {
it('should render index view', function (done) {
chai
.request(server.app)
.get('/')
.end(function (err, res) {
console.log(res.body);
done();
});
});
});
test result:
Homepage
{ list: [ 'a', 'b' ] }
✓ should render index view
1 passing (28ms)
Option 2. You should assert the view rendered correctly with your list data.
index.js:
var express = require('express');
var path = require('path');
var app = express();
app.set('views', path.resolve(__dirname, './views'));
app.set('view engine', 'ejs');
app.get('/', function (req, res) {
const data = ['a', 'b'];
res.render('index', { list: data });
});
module.exports = { app };
views/index.ejs:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<% for (let v of list) { %>
<p><%= v %></p>
<% } %>
</body>
</html>
index.test.js:
const { expect } = require('chai');
var chai = require('chai');
var chaiHttp = require('chai-http');
var server = require('./index');
var should = chai.should();
chai.use(chaiHttp);
describe('Homepage', function (done) {
it('should render index view', function (done) {
chai
.request(server.app)
.get('/')
.end(function (err, res) {
console.log(res.text);
done();
});
});
});
test result:
Homepage
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<p>a</p>
<p>b</p>
</body>
</html>
✓ should render index view
1 passing (32ms)