hello this is my first post.
I'm a beginner of coding, so i watching video of opentutorials.org/course/2136/11950
i tried to find error in my code. but i can't not TT
When we enter site, it shows data lists.
[localhost:3000/topic]
enter image description here
and click the list, it shows description.
like this.
enter image description here
but in my case.. every text makes li... how can i do?
enter image description here
//app.js
const express = require('express'); //가져오기
const bodyParser = require('body-parser');//가져오기
const fs = require('fs');
const { title } = require('process');
const app = express();
app.use(bodyParser.urlencoded({extended:false})); //bodyParser를 사용하겠다.
app.locals.pretty = true;
app.set('views', './views') //템플릿엔진 위치 설정
app.set('view engine', 'pug')//어떤 엔진사용할건지 설정
app.get('/topic/new', (req, res) => res.render('new') );
app.get('/topic', (req, res) => {
fs.readdir('data',(err, data) => {
if(err){//에러가 있다면
res.status(500).send('Internal Server Error');
}
res.render('view', {topics : data}); //사용자가 topic에들어오면 글목록보이기
})
} );
app.get('/topic/:id',(req, res)=>{
const id = req.params.id;
fs.readdir('data',(err, data)=>{
if(err){
res.status(500).send('Internal Server Error');
}
})
fs.readFile('data/'+id, 'utf8', (err, data) =>{
if(err){//에러가 있다면
res.status(500).send('Internal Server Error');
}
res.render('view',{title:id, topics : data, description:data });
})
})
//바뀌는정보를 콜론+변수명
app.post('/topic',(req, res) =>
{
const title = req.body.title;
const description = req.body.description;
//파일을 쓰게하기
fs.writeFile('data/'+title, description,(err)=> { //data폴더에 title로 파일명, 내용은 description
if(err){//에러가 있다면
res.status(500).send('Internal Server Error');
}
res.send('Success!')
});
});
app.listen(3000, () => { console.log('connected 3000 port!')}) //port, 콜백(서버연결시 출력)
//view.pug
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
body
h1 Server Side JavaScript
ul
each topic in topics
li
a(href="/topic/"+topic)= topic
article
h2= title
The render variable in app.get('/topic/:id') is incorrectly set. The below changes should render your view properly
app.get('/topic/:id',(req, res)=>{
const id = req.params.id;
let filesList = null
fs.readdir('data',(err, data)=>{
if(err){
res.status(500).send('Internal Server Error');
}
// This variable should be returned for topics
filesList = data
})
fs.readFile('data/'+id, 'utf8', (err, data) =>{
if(err){//에러가 있다면
res.status(500).send('Internal Server Error');
}
// Update the topics variable
res.render('view',{title:id, topics : filesList, description:data });
})
})
Related
I Am developing a Node API for employee department model
for which i developed couple of Request Like 'GET PUSH PATCH DELETE' (CRUD Operation)
for both end employee & department
i am developing on my local server
here's my app.js looks like
const http=require('http');
const app =require('./app');
const port =process.env.PORT || 3000;
const server = http.createServer(app);
server.listen(port);
console.log('Server Has Been Started');
console.log('localhost:'+port);
And On the listner side here's my app.js looks like
// Dependency
const express = require('express');
const app = express();
const morgan =require('morgan');
const bodyParser =require('body-parser');
const mongoose =require('mongoose');
// Importing routes
const employeeRoutes =require('./api/routes/employee');
const departmentRoutes =require('./api/routes/department');
app.use(morgan('dev'));
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
// Header Defination to Avoid Corp's
app.use((req, res ,next) =>
{
res.header("Access-Control-Allow-Origin","*");
res.header(
"Access-Control-Allow-Headers",
"Origin,X-Requested-With,Content-Type,Accept,Authorization"
);
if (req.method === 'OPTIONS')
{
res.header('Access-Control-Allow-Methods','PUT,POST,PATCH,DELETE,GET');
return res.status(200).json({});
}
});
// Routes for api
app.use('/employee',employeeRoutes);
app.use('/department',departmentRoutes);
// Error Handling
app.use((req, res, next) =>
{
const error =new Error('Not Found');
error.status =404;
next(error);
});
app.use((error, req, res, next) =>
{
res.status(error.status ||500);
res.json({
error:{
message:error.message
}
});
});
module.exports = app;
in order to send request and receiving response as a json on other end
i developed employee .js and department .js with GET PUSH PATCH DELETE
here's my both file looks like
./api/routes/employee.js
it just showcase script to validate code is working or not
const express = require('express');
const router =express.Router();
const mongoose =require('mongoose');
const Employee =require('../models/Employee');
router.get('/',(req, res ,next) => {
res.status(200).json({
message:'Handling GET request to ./employees'
});
});
router.post('/',(req, res ,next) => {
res.status(201).json({
message:'Handling POST request to ./employees',
});
});
router.get('/:employeeId',(req, res ,next) =>
{
const id =req.params.employeeId;
if (id === 'special'){
res.status(200).json({
message: 'You Discovered A speacial ID',
id:id
});
} else
{
res.status(200).json({
message:'You passed an ID'
});
}
});
router.patch('/:employeeId',(req, res ,next) =>
{
res.status(200).json({
message:'Updated Employees'
});
});
router.delete('/:employeeId',(req, res ,next) =>
{
res.status(200).json({
message:'Deleted Employee'
});
});
module.exports =router;
../api/routes/department.js
const express = require('express');
const router =express.Router();
router.get('/',(req, res ,next) =>{
res.status(200).json({
message:'Department fetched'
});
});
router.post('/',(req, res ,next) =>{
const department={
name:req.body.name,
Id:req.body.Id
};
res.status(201).json({
message:'Department created',
createdDepartment:department
});
});
router.get('/:departmentId',(req, res ,next) =>{
res.status(200).json({
message:'Department Details',
departmentId: req.params.departmentId
});
});
router.delete('/:departmentId',(req, res ,next) =>{
res.status(200).json({
message:'Department Deleted',
departmentId: req.params.departmentId
});
});
router.patch('/:departmentId',(req, res ,next) =>
{
res.status(200).json({
message:'Department Updated',
departmentId :req.params.departmentId
});
});
module.exports =router;
Now when i try to run this code in as permy coding experience it has no logical error
also on terminal it showed
terminal o/p
but when i try to run in postman
it just loading not response is coming back
likepostman o/p
and also on web like
web o/p
and then onto terminal be like
terminal after get not respond still server is running
i know there is problem with connection but i double check all the possible way like proxy and firewall disabled
also i tried to delter node module and package.json(lock) and reinstalled it nothing of them is working
and when i stop the server postman show socket hangup
sockethangup postman
i wanna to know where i am lacking with meaninf ful answer
Add next() to pass the request to the next middleware after the CORS section.
// Header Defination to Avoid Corp's
app.use((req, res ,next) =>
{
res.header("Access-Control-Allow-Origin","*");
res.header(
"Access-Control-Allow-Headers",
"Origin,X-Requested-With,Content-Type,Accept,Authorization"
);
if (req.method === 'OPTIONS')
{
res.header('Access-Control-Allow-Methods','PUT,POST,PATCH,DELETE,GET');
return res.status(200).json({});
}
// Pass next middleware
next();
});
I am trying to create a pdf from rendered ejs file but cannot render image properly no matter how I try.
my app.js :
let express = require("express");
let app = express();
let ejs = require("ejs");
let pdf = require("html-pdf");
let path = require("path");
app.use( express.static( "public" ) );
app.get("/generateReport", (req, res) => {
ejs.renderFile("./views/report-template.ejs", (err, data) => {
if (err) {
res.send(err);
} else {
pdf.create(data).toFile("certificate.pdf", function (err, data) {
if (err) {
res.send(err);
} else {
res.send("File created successfully");
}
});
}
});
})
app.listen(3000, function(){
console.log('Server listening on port 3000');
});
----------
my report-template.ejs file
<html>
<body>
<img src="certificate.jpg" width=675 height=792>
</body>
</html>
I've saved certificated.jpg in all the locations including root,public etc..but it does'nt work..Please help ..I'm new to coding and node.
this work for me, parameter "base" in options pdf
//base: ${req.protocol}://${req.get('host')}
var options = {
"format": "A4",
"orientation": "portrait",
base: `${req.protocol}://${req.get('host')}`,
};
pdf.create(resulthtml, options).toStream(function(err, stream) {
if (err) res.end('An error occurred on create pdf');
res.setHeader('Content-disposition', 'inline; filename="' + stream.filename + '"');
res.setHeader('Content-type', 'application/pdf');
stream.pipe(res);
});
then now in template
<img src="/public/image.png">
or simply
<img src="image.png">
I working on my API for the E-commerce app in MERN. I have done a few things already, and now I am trying to get single category. There is no error on console, and I read the code a few times, but postman keeps throwing Cannot GET error. I would appreciate it if someone can tell me what's the deal with this.
The part for creating new category works just fine, also as similar code for getting one product Code:
Category.js Router
const express = require("express");
const router = express.Router();
const { create, categoryById, get } = require("../controllers/category");
const { requireSignin, isAuth, isAdmin } = require("../controllers/auth");
const { userById } = require("../controllers/user");
router.get("/category/:categoryId", get);
router.post("/category/create/:userId", requireSignin, isAuth, isAdmin, create);
router.param("categoryId", categoryById);
router.param("userId", userById);
Category.js Controller
const Category = require("../models/category");
const { errorHandler } = require("../helpers/dbErrorHandler");
exports.categoryById = (req, res, next, id) => {
Category.findById(id).exec((err, category) => {
if(err || !category) {
return res.status(400).json({
error: 'Category does not exist'
});
}
req.category = category;
next();
});
}
exports.create = (req, res) => {
const category = new Category(req.body);
category.save((err, data) => {
if (err) {
return res.status(400).json({
error: errorHandler(err)
});
}
res.json({ data });
});
};
exports.get = (req, res) => {
return res.json(req.category);
}
I'm new at programming and I've been trying to make a post that allows me to send data from an ancount form into a table( mysql database). However the console.log(on the node node console shows me an error) and I can't seem to understand why the post isn't working.
I get the error cannot enqueue Handshake after already enqueuing a Handshake, even though I've googled about, I haven't found a way to make the post work or get rid of this error.
Appreciate for any help.
const express = require('express');
const mysql = require('mysql');
// Create connection
const db = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'nodemysql'
});
// Connect
db.connect((err) => {
if(err){
throw err;
}
console.log('MySql Connected...');
});
const app = express();
app.get('/', function (req, res) {//nome da minha url req(é o que vai na url/ res é o response é o ficheiro)
res.sendFile(path.join(__dirname+'/public/index.html'));
})
app.get('/log_in', function (req, res) {//nome da minha url
res.sendFile(path.join(__dirname+'/public/signin.html'));
})
app.get('/register', function (req, res) {//nome da minha url
res.sendFile(path.join(__dirname+'/public/register.html'));
})
// Create DB
app.get('/createdb', (req, res) => {
let sql = 'CREATE DATABASE IF NOT EXISTS nodemysql';
db.query(sql, (err, result) => {
if(err) throw err;
console.log(result);
res.send('Database created...');
});
});
// Create table
app.get('/createusertable', (req, res) => {
let sql = 'CREATE TABLE user (id int AUTO_INCREMENT, name VARCHAR(50), last_name VARCHAR(50),email VARCHAR(100),password VARCHAR (100),phone VARCHAR (50),country VARCHAR(100),vat_number VARCHAR(9),address VARCHAR(150), PRIMARY KEY(id))';
db.query(sql, (err, result) => {
if(err) throw err;
console.log(result);
res.send('Post table created...');
});
});
db.connect(function(err){
if(err) return console.log(err);
console.log('conectou!');
createTable(connection);
})
app.listen('3000', () => {
console.log('Server started on port 3000');
});
app.use(express.static('public'))
const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.post('/register', function (req, res) {
console.log(req.body.user.name);
let post = {name:req.body.user.name, last_name:req.body.user.lastName,
email:req.body.user.email, password:req.body.user.password, phone:req.body.user.phone,
country:req.body.user.country, vat_number:req.body.user.nif, address:req.body.user.address};
let sql = 'INSERT INTO user SET ?';
let query = db.query(sql, post, (err, result) => {
if(err) throw err;
res.redirect(303,'/');
});
});
It looks like you initiate another db.connect in your create table step after you already initiated a connect in the beginning of your script.
This is a double connection initiation, without any connection.end(); to close the initially opened connection.
I think you will have more luck when you remove the db.connect from your "create table" step.
Please view this documentation to further clarify my point.
This is my first ever posting on the stackover flow so excuse me if I am breaking any kind of rules.
I am trying to implement a tutorial related to "Make API on Node.js with express" and I am getting this error.
"Invalid regular expression: /^?(?:([^/]+?))/?$/:"
var express = require('express')
var bookRouter=express.Router();
var Book=require('/Users/home/Desktop/ExpressProject/Models/bookModels.js')
var bodyParser=require('body-parser');
bookRouter.route('/')
.get((req, res) => {
Book.find({}, (err, books) => {
res.json(books)
})
})
.post((req, res) => {
let book = new Book(req.body);
book.save();
res.status(201).send(book)
})
// Middleware
bookRouter.use('/:bookId', (req, res, next)=>{
Book.findById( req.params.bookId, (err,book)=>{
if(err)
res.status(500).send(err)
else {
req.book = book;
next()
}
})
})
bookRouter.route('/:bookId')
.get((req, res) => {
res.json(req.book)
}) // end get Books/:bookId
.put((req,res) => {
req.book.title = req.body.title;
req.book.author = req.body.author;
req.book.save()
res.json(req.book)
})
.patch((req,res)=>{
if(req.body._id){
delete req.body._id;
}
for( let p in req.body ){
req.book[p] = req.body[p]
}
req.book.save()
res.json(req.book)
})//patch
.delete((req,res)=>{
req.book.remove(err => {
if(err){
res.status(500).send(err)
}
else{
res.status(204).send('removed')
}
})
})//delete
module.exports =bookRouter;
I am completely new to programming so also excuse if I am asking something to lame