cannot get/ posts error on localhost:5000/posts (I tried router .get ('/posts', getPosts); but didn't resolved - mern

Here is my server side of folder routes/ post.js file
//server/routes/post.js
import express from 'express';
import {getPosts, createPost} from
'../controllers/posts.js'
const router = express.Router();
router.get('/' , getPosts);
router.get ('/posts', getPosts);
router.post('/' ,createPost);
export default router;
Here is my server folder of controllers/file posts.js file
//server/controllers/posts.js
import PostMessage from '../models/postMessage.js';
export const getPosts = async(req, res) => {
try {
const postMessages = await PostMessage.find();
res.status(200).json(postMessages);
} catch (error) {
res.status(404).json({message: error.message});
}
}
export const createPost = (req, res) => {
res.send('Post Creation');
}
Here is my server in which folder models/file postMessage.js postMessage.js code;
server/models/postMessage.js
import mongoose from 'mongoose';
const postSchema = mongoose.Schema({
title: String,
message: String,
creator: String,
tags: [String],
selectedFile: String,
likeCount: {
type: Number,
default: 0
},
createdAt : {
type: Date,
default: new Date()
},
});
const PostMessage = mongoose.model ('PostMessage',
postSchema);
export default PostMessage;

Related

invalid json response body at http://localhost:3000/api/user/[object%20Object] reason: Unexpected token < in JSON at position 0

I'm using this example to create a simple authentication with Nextjs https://github.com/vvo/next-iron-session/tree/master/examples/next.js
but instead of fetching the user JSON object from Github (as the example does) im trying to do it from my mongodb database where i have some users.
I did this on my login.js file:
import fetchJson from "../../lib/fetchJson";
import withSession from "../../lib/session";
import { withIronSession } from "next-iron-session";
import { connectToDatabase } from "../../util/mongodb";
export default withSession(async (req, res) => {
const { db } = await connectToDatabase();
const { username } = await req.body;
const foundUser = await db.collection("users").findOne({"userName": username});
console.log(foundUser) // <--- this returns the user object on console just fine
const url = `http://localhost:3000/api/user/${foundUser}`;
try {
const { userName, email } = await fetchJson(url);
const user = { isLoggedIn: true, userName, email }
req.session.set("user", user);
await req.session.save();
res.json(user);
} catch (error) {
const { response: fetchResponse } = error;
res.status(fetchResponse?.status || 500).json(error.data);
}
});
And i have this code on my /api/user.js file:
import withSession from "../../lib/session";
import { connectToDatabase } from "../../util/mongodb";
export default withSession(async (req, res) => {
const user = req.session.get("user");
if (user) {
const { db } = await connectToDatabase();
const foundUser = await db.collection("users").findOne({"userName": user.userName, "email": user.email});
console.log("useri pi te user.js " + foundUser)
// in a real world application you might read the user id from the session and then do a database request
// to get more information on the user if needed
res.json({
isLoggedIn: true,
...user,
});
} else {
res.json({
isLoggedIn: false,
});
}
});
But i get "invalid json response body at http://localhost:3000/api/user/[object%20Object] reason: Unexpected token < in JSON at position 0" error even though i get the user object printed in the console just fine.
Any help would be appreciated!

findAll() return [object SequelizeInstance:table name] (mysql)

my code is :
app.get('/main', function(req, res) {
Posts.findAll().then(function(posts){
res.render(__dirname + "/home.pug", {posts:posts});
})
at node and :
div
each val in posts
li= val
at pug, but it return:[object SequelizeInstance:mensages](mensages is the database name) instead the value
sorry for my English and if the question is confuse
Because you are trying to render the model instances of sequelize returned by Posts.findAll() method.
You maybe want to render a property of post, not the entire model instance object.
E.g.
app.ts:
import express from 'express';
import path from 'path';
import { DataTypes, Model } from 'sequelize';
import { sequelize } from '../../db';
class Posts extends Model {}
Posts.init(
{
name: DataTypes.STRING,
},
{ sequelize, tableName: 'posts' },
);
const app = express();
app.set('view engine', 'pug');
app.set('views', path.resolve(__dirname, './views'));
app.get('/', (req, res) => {
Posts.findAll().then(function(posts) {
res.render('home.pug', { posts: posts });
});
});
(async function main() {
await sequelize.sync({ force: true });
//seed
await Posts.bulkCreate([{ name: 'teresa' }, { name: 'teng' }]);
app.listen(3000, () => console.log('Server started at http://localhost:3000'));
})();
views/home.pug:
<!DOCTYPE html>
html(lang="en")
head
meta(charset="UTF-8")
meta(name="viewport", content="width=device-width, initial-scale=1.0")
title Document
body
div
each val in posts
li= val.name
HTML output:
source code: https://github.com/mrdulin/node-sequelize-examples/tree/master/src/examples/stackoverflow/65376890

Module not found: Can't resolve 'fs' in '.../node_modules/destroy' using Next.js mysql Express React

I would like to insert data from pages/index.js into mysql database.
A mysql connection in routes/routes.js, i have built ins function to call what i want
Structure
components
pages
index.js
routes
routes.js
server.js
package.json
Fail with error:
Module not found: Can't resolve 'fs' in '.../node_modules/destroy'
pages/index.js
import React, { Component } from "react";
import { Typography, Button, Grid } from "#material-ui/core";
import QRCode from "qrcode.react";
import dynamic from "next/dynamic";
import { PublicKey, SecretKey, HOSPCODE } from "../stellar";
const { ins } = require("../routes/routes"); //This is the problem!
const StellarSdk = require("stellar-sdk");
const QrReader = dynamic(() => import("react-qr-reader"), {
ssr: false
});
export default class QR extends Component {
state = {
result: "",
camera: true,
msg: "",
QR: {}
};
_clear = () => {
this.setState({ result: "", camera: true, msg: "", QR: {} });
};
handleScan = data => {
if (data) {
const dataJson = JSON.parse(data);
if (dataJson.Type == "Patient") {
const KP = StellarSdk.Keypair.fromSecret(SecretKey);
this.setState({
result: dataJson,
QR: JSON.stringify({
Type: "Hospital",
HospitalName: "xxx Hospital",
EndPoint: "xxx/patientID_",
SPK: PublicKey,
Signature: KP.sign(
Buffer.from(dataJson.ID + dataJson.SPK)
).toString("base64")
}),
camera: false,
msg: ""
});
ins(dataJson.ID, HOSPCODE, dataJson.SPK, dataJson.SecretKey);
} else {
this.setState({
msg: "Wrong QRCode."
});
}
}
};
But /routes/routes in server.js work.
const express = require("express");
const next = require("next");
const dev = process.env.NODE_ENV !== "production";
const app = next({ dev });
const handle = app.getRequestHandler();
const bodyParser = require("body-parser");
const { router, ins } = require("./routes/routes");
app
.prepare()
.then(() => {
const server = express();
server.use(bodyParser.json());
server.use(bodyParser.urlencoded({ extended: false }));
server.use("/api", router);
server.get("*", (req, res) => {
return handle(req, res);
});
server.listen(3001, err => {
if (err) throw err;
console.log("> Ready on http://localhost:3001");
});
})
.catch(ex => {
console.error(ex.stack);
process.exit(1);
});
routes/routes.js
const express = require("express");
const mysql = require("mysql");
const router = express.Router();
const dotenv = require("dotenv").config();
const connection = mysql.createConnection({
host: process.env.DATABASE_HOST,
database: process.env.DATABASE_NAME,
user: process.env.DATABASE_USERNAME,
password: process.env.DATABASE_PASSWORD,
port: 3306
});
console.log("Connecting...");
connection.connect(function(err) {
if (err) return new Error("An error occured during SQL connection " + err);
console.log("Connected!");
});
console.log(connection.config);
/* GET home page. */
router.get("/", function(req, res, next) {
...
...
...
ins = (cid, HOSPCODE, spk, secretKey) => (cid, HOSPCODE, spk, secretKey) => {
var sql = "INSERT INTO STELLARKEY (CID, HOSPCODE, SPK, SecretKey) VALUES ?";
var values = [[cid, HOSPCODE, spk, secretkey]];
connection.query(sql, [values], function(err, result) {
if (err) throw err;
});
};
module.exports = { router, ins };
I am new at Next.js and React. There is a better way to insert data from pages/index.js into mysql database? Please let me know.
"dependencies": {
"#material-ui/core": "^4.9.0",
"#material-ui/icons": "^4.5.1",
"body-parser": "^1.19.0",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"fs": "^0.0.1-security",
"mysql": "^2.18.1",
"next": "^9.2.1",
"qrcode.react": "^1.0.0",
"react": "^16.12.0",
"react-dom": "^16.12.0",
"react-qr-reader": "^2.2.1",
"stellar-sdk": "^3.3.0",
"typeface-roboto": "^0.0.75"
}
Ubuntu 18.04 x64,
mysql Ver 14.14 Distrib 5.7.28,
Node v12.14.1
At last, i have to post request to my server via the same server on frontend(index.js) to insert data into mysql database.
I'm not sure. because of SSR(Next.js), i cannot send data back to backend.
But
I still need other method except post request into itself.
routes/routes.js
router.post("/secret/", cors(corsOptions), function(req, res, next) {
var sql = "INSERT INTO STELLARKEY (CID, HOSPCODE, SPK, SecretKey) VALUES ?";
var values = [
[req.body.cid, req.body.HOSPCODE, req.body.spk, req.body.secretkey]
];
connection.query(sql, [values], function(err, result) {
if (err) console.log(err);
});
});
module.exports = router;
pages/index.js
fetch("http://localhost:3001/api/secret", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({
cid: dataJson.ID,
HOSPCODE: HOSPCODE,
spk: dataJson.SPK,
secretkey: dataJson.SecretKey
})
});
server.js
const router = require("./routes/routes");
app
.prepare()
.then(() => {
const server = express();
server.use(bodyParser.json());
server.use(bodyParser.urlencoded({ extended: false }));
server.use("/api", router);
server.get("*", (req, res) => {
return handle(req, res);
});
As long as we don't run next build and don't start app with NODE_ENV=production, this issue won't happen.
We use NODE_ENV=dev to circumvent this issue for the moment. I mean we use npm run dev to deploy now. This can only be considered a temporary solution.
"scripts": {
"dev": "NODE_ENV=dev node server.js",
"start": "node server.js",
"deploy": "next build && NODE_ENV=production node server.js"
}

Angular sending a request to node api

In my angular app, I send a post request to node API with JSON data object, but it doesn't work as intended. In the request payload, the JSON data object is not shown.
When i send a JSON string by using JSON.stringify(auth) it's shown in the request payload but can't be parsed by the json body-parser at the node backend. Requests body is empty. Give me a solution to this problem.
My code
import { Injectable } from "#angular/core";
import { AuthData } from "../modules/AuthData";
import {
HttpClient,
HttpParams,
HTTP_INTERCEPTORS,
HttpInterceptor,
HttpHeaders
} from "#angular/common/http";
#Injectable({
providedIn: "root"
})
export class AuthService {
private url = "http://localhost:3000";
private httpOptions = {
headers: new HttpHeaders({
"Content-Type": "application/json",
Authorization: "my-auth-token",
"Request-Method": "post"
})
};
constructor(private http: HttpClient) {}
login(email: string, password: string) {
const authData = { email: email, password: password };
console.log(authData);
this.http
.post(this.url + "/api/user/login", authData)
.subscribe(response => {
console.log(response);
});
}
}
My backend code
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const mongoose = require("mongoose");
const cors = require('cors');
const userRoute = require("./routes/user");
const app = express();
mongoose
.connect('mongodb://localhost:27017/tryondb', {
useNewUrlParser: true
})
.then(() => {
console.log("connected to the database");
})
.catch(() => {
console.log("connection failed");
})
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:false}));
//var jsonParser = bodyParser.json();
//var urlencodedParser = bodyParser.urlencoded({ extended: false });
//app.use(cors);
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader(
"Access-Control-Allow-Header",
"Origin, X-Requested-with, Content-Type, Accept"
);
res.setHeader(
"Access-Control-Allow-Methods",
"GET, POST, PATCH, DELETE, OPTIONS"
);
console.log("rrr");
next();
})
app.post("/api/user/login",(req,res,next)=>{
console.log(req);
});
app.use("/api/user", userRoute);
console.log("aaa");
module.exports = app;
you are creating httpoptions but you are not passing them correctly: try
login(email: string, password: string) {
const authData = { email: email, password: password };
console.log(authData);
this.http
.post(this.url + "/api/user/login", authData, httpOptions)
.subscribe(response => {
console.log(response);
});
}

Can't get data form nodejs by angular

Hi I can't get data from nodejs by angular 6.
I added a service to connect between them but it is not working.
I succeed to get data by nodejs server, but I can't receive it on angular components.
I know that I missed something to connect between them but I can't resolve it.
HostingstartComponent.ts
import { Component, OnInit } from '#angular/core';
import { NgAnalyzedFile } from '#angular/compiler';
import {RouterModule ,Routes } from '#angular/router';
import {HttpModule, Http} from '#angular/http'
import { AngularFontAwesomeModule } from 'angular-font-awesome';
import { SecComponent } from '../sec/sec.component';
import { ThirdComponent } from '../third/third.component';
import {aService} from '../services/a.service';
#Component({
selector: 'app-hostingstart',
templateUrl: './hostingstart.component.html',
styleUrls: ['./hostingstart.component.css']
})
export class HostingstartComponent implements OnInit {
aService: any;
data: any;
appRoutes : Routes=[
{path: 'hostingstar',component : HostingstartComponent},
{path: '',component : HostingstartComponent},
{path: 'sec',component : SecComponent, data : {some_data : 'some value'}},
{path: 'third',component : ThirdComponent, data : {some_data : 'some value'}}
];
headImg : any="assets/images/pan.JPG";
constructor(private http: Http , private service: aService) {
this.headImg ="assets/images/pan.JPG";
// this.aService.getData().then( (result) => {this.data = result; });
}
ngOnInit() {
// alert(this.aService.getData());
// this.aService.getData().then( (result) => {this.data = result; });
// alert(this.data);
}
myFunc() {
//this.router.navigate(['/third', 'north']);
// alert( document.getElementById("search-input").value);
}
getData() {
this.aService.getData().subscribe((dataFromServer) => {
this.data=dataFromServer;
// Now you can use the data
// alert(dataFromServer)
console.log(dataFromServer);
});
}
}
aService.ts
import 'rxjs/add/operator/toPromise';
import { Http, Response, Headers } from '#angular/http';
import { Injectable } from '#angular/core';
#Injectable()
export class aService {
constructor(private http: Http) {
}
async getData() {
const options = {
headers: new Headers({
'Content-Type': 'application/json;charset=utf-8',
'Access-Control-Allow-Origin': '*'
})
};
// const url = './assets/heroes.data.json';
const url = 'http://localhost:3000/';
return this.http.get(url, options)
.toPromise()
.then(response => {
if (response != null) {
const result = response.json();
return Promise.resolve(result);
}
return [];
})
.catch(err => {
console.warn('error in getCats', err);
return Promise.reject(null);
});
}
}
Node js : index.js
console.log('Running File: index.js')
//-- Create Express Server:
var express = require('express');
var app = express();
var util = require('util');
var mysql = require('mysql');
var a;
var con = mysql.createConnection({
host : 'localhost',
user: 'node',
password : 'arafat1990!##$',
database: "iTour"
});
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM feedback", function (err, result, fields) {
if (err) throw err;
// console.log(result);
a=result;
});
});
//-- Map Base URL to res (Response)
app.get('/', function(req, res){
var fname = req.query.fname;
var lname = req.query.lname;
var html = util.format('<p>Hello %s %s</p>', a[1].username,a[0].rating);
res.send(a);
});
app.get('/hostingstar', function(req, res){
var fname = req.query.fname;
var lname = req.query.lname;
var html = util.format('<p>Hello %s %s</p>', a[1].username,a[0].rating);
res.send(a);
});
//-- Listen on Port 3000:
app.listen(3000);
app.js
const express = require('express');
const app = express();
//const firebase = require('firebase-admin');
app.get('/hostingstart', (req, res) => res.send('Server Is Active!'))
app.get('/hostingstart', (req, res) => {
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user: 'node',
password : 'arafat1990!##$',
database: "iTour"
});
connection.connect();
connection.query('SELECT * FROM feedback;', function (error, results, fields) {
if (error) {
console.warn(error);
res.send('');
return;
}
console.log("Result: " + results);
res.send(results);
});
connection.end();
})
app.get('/hostingstart', (req, res) => {
var ref = firebase.app().database().ref();
ref.once("value").then(function (snap) {
console.log("snap.val()", snap.val());
res.send(snap.val());
});
});
app.use(function(req, res, next){
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Credentials", "true");
res.setHeader("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
res.setHeader("Access-Control-Allow-Headers", "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");
// Check if preflight request
if (req.method === 'OPTIONS') {
res.status(200);
res.end();
}
else {
next();
}
});
app.listen(3000, () => console.log('Server is listening on port 3000!'))
In your getService method you are calling the service itself not the property from the constructor.
Your:
this.aService.getData()
Should be:
this.service.getData()
Additionally call myFunc() in ngOnInit
ngOnInit() {
this.myFunc()
}