Sending data on server by fetch - javascript

Can someone explain to me why after sending a request, server returns POST {} {}- I mean empty objects?
I don't know where this data is. Why did it dissapear?
I have no idea how to solve it...
index.js:
window.addEventListener("DOMContentLoaded", () => {
const form = document.querySelector("form");
form.addEventListener("submit", event => {
console.log("włącza sie");
event.preventDefault();
const name = document.getElementById("name").value;
const password = document.getElementById("password").value;
fetch("http:localhost:3000/register", {
method: "POST",
body: JSON.stringify({ name, password })
})
.then(res => {
console.log(res);
})
.catch(error => console.log(error));
});
});
//server.js:
const http = require("http");
const app = require("./app");
const port = 3000;
const server = http.createServer(app);
server.listen(port, () => {
console.log("server włączony");
});
//app.js
const loginRoute = require("./api/routes/loginRoute");
const registerRoute = require("./api/routes/registerRoute");
const verify = require("./autorization/verify");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use("/", (req, res, next) => {
console.log(req.method, req.query, req.body);
next();
});
app.use("/", loginRoute);
app.use("/", registerRoute);
app.use(verify);

based from your screenshot, there's a CORS issue. You can overcome that using
https://github.com/expressjs/cors middleware
var cors = require('cors');
app.use(cors());
or enable CORS for the specific route only
app.use('/', cors(), registerRoute);

registerRoute:
const express = require('express');
const router = express.Router();
const register = require('../../mongo/register');
router.post('/register',register);
module.exports = router;
register.js:
const mongo = require('./database');
const User = require('../api/patterns/user');
const register = (req,res)=>{
const toSave = new User(req.body);
User.findOne({name: req.body.name},(err,name)=>{
if(err) throw err;
if(!name){
toSave.save( (err)=> {
if (err) throw err;
console.log('user zapisany');
});
}else{
console.log('juz taki istnieje');
}
});
};
app.js:
const loginRoute = require('./api/routes/loginRoute');
const registerRoute = require('./api/routes/registerRoute');
const verify = require('./autorization/verify');
var cors = require('cors');
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use('/', (req,res,next)=>{console.log(req.method, req.query, req.body);
next();});
app.use('/', loginRoute);
app.use('/', registerRoute);
app.use(verify);
module.exports = app;
It still returns empty objects :(

Related

TypeError: app.use() requires a middleware function No clue why error

so I am getting the the error : TypeError: app.use() requires a middleware function.
I am unsure why i made sure i exported the file, but I am a bit confused why. I think i linked it up correctly in my server file as well.
const express = require('express')
const mongoose = require('mongoose')
const morgan = require('morgan')
const app = express()
const bodyParser = require('body-parser')
app.use(morgan('dev'))
require('dotenv').config()
const { expressjwt: jwt } = require("express-jwt")
app.use(bodyParser.json())
mongoose.connect('mongodb://localhost:27017/recipe', ()=> console.log('connected to database'))
app.use('/auth', require('./routes/authRouter'))
app.use("/api", jwt( {secret: process.env.SECRET, algorithms: ['HS256']}))
app.use('/api/recipe/', require('./routes/recipeRoutes'))
app.use('/api/public/'), require('./routes/publicDelete')
app.use('/api/comments/', require('./routes/commentRouter'))
app.use('/api/ingredients/', require('./routes/ingredRouter'))
app.use((err,req,res,next)=>{
console.log(err)
if(err.name ==='UnauthorizedError'){
res.status(err.status)
}
return res.send({message:err.message})
})
app.listen(8000, ()=>{
console.log('hello ')
})
const express = require('express')
const publicDeleteRouter = express.Router()
const Recipe = require('../models/recipe')
const User = require('../models/user')
publicDeleteRouter.delete('/:recipeId', (req, res, next) =>{
Recipe.findOneAndDelete({idMeal: req.params.recipeId, user: req.auth._id}, (err, deletedRecipe) => {
if(err){
console.log(idMeal)
res.status(404)
return next(err)
}
console.log('successfully deleted: ', deletedRecipe)
return res.status(200).send(`Successfully deleted ${deletedRecipe}`)
})
})
module.exports = publicDeleteRouter

login authorization problem, does not pass the token

I am trying to make a login system with authorization, unfortunately the token is not transferred.
const path = require('path');
const express = require('express');
const bodyParser = require('body-parser');
const urlencodedParser = bodyParser.urlencoded({ extended: false });
const mysql = require('mysql');
const validator = require('validator');
const jwt = require('jsonwebtoken');
require('dotenv').config().ACCESS_TOKEN;
const ACCESS_TOKEN = process.env.ACCESS_TOKEN;
const app = express();
app.use(express.json());
const publicDirectoryPath = path.join(__dirname, '../public');
console.log(publicDirectoryPath);
app.use(express.static(publicDirectoryPath));
function generateAccessToken(username) {
return jwt.sign(username, ACCESS_TOKEN, { expiresIn: '1800s' });
}
app.post('/login', urlencodedParser, (req, res) => {
res.get(req.body.username + req.body.password);
const token = generateAccessToken({ username: req.body.username });
res.json(token);
});
function authenticateToken(req, res, next) {
const authHeader = req.headers['authorization']
const token = authHeader && authHeader.split(' ')[1]
console.log(token)
if (token == null) return res.sendStatus(401)
jwt.verify(token, ACCESS_TOKEN, (err, user) => {
console.log(err)
if (err) return res.sendStatus(403)
req.user = user
next()
})
}
app.get('/admin', authenticateToken, (req, res) => {
res.send("admin panel");
})
const port = 3000;
app.listen(port, () => {
console.log(`Server run: http://localhost:${port}`);
})
wants him to be redirected to the admin panel after clicking the login button. However, I am stuck at this stage and do not know what to do next:
enter image description here
You should pass the token to the next route
const path = require('path');
const express = require('express');
const bodyParser = require('body-parser');
const urlencodedParser = bodyParser.urlencoded({ extended: false });
const mysql = require('mysql');
const validator = require('validator');
const jwt = require('jsonwebtoken');
require('dotenv').config().ACCESS_TOKEN;
const ACCESS_TOKEN = process.env.ACCESS_TOKEN;
const app = express();
app.use(express.json());
const publicDirectoryPath = path.join(__dirname, '../public');
console.log(publicDirectoryPath);
app.use(express.static(publicDirectoryPath));
function generateAccessToken(username) {
return jwt.sign(username, 'ACCESS_TOKEN', { expiresIn: '1800s' });
}
app.post('/login', urlencodedParser, (req, res) => {
res.get(req.body.username + req.body.password);
const token = generateAccessToken({ username: req.body.username });
res.redirect(`/admin?token=${token}`);
});
function authenticateToken(req, res, next) {
token = req.query.token;
if (token == null) return res.sendStatus(401);
jwt.verify(token, 'ACCESS_TOKEN', (err, user) => {
console.log(err);
if (err) return res.sendStatus(403);
req.user = user;
next();
});
}
app.get('/admin', authenticateToken, (req, res) => {
res.send('admin panel');
});
const port = 3000;
app.listen(port, () => {
console.log(`Server run: http://localhost:${port}`);
});

how do I redirect to another page?

I want to make a redirect to another page if the data is inserted, but for some reason it does not work. please tell me how you can do this? there were different ways, but even argulatorjs didn't help.
let express = require("express");
let app = express();
let port = 3000;
let bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
let angular = require('angular');
let mongoose = require("mongoose");
mongoose.Promise = global.Promise;
mongoose.connect("mongodb://localhost:27017/test");
let nameSchema = new mongoose.Schema({
name: String,
login: String,
password: String,
authorization: Boolean
});
let User = mongoose.model("User", nameSchema);
app.get("/", (req, res) => {
res.sendFile(__dirname + "/index.html");
});
app.post("/addname", (req, res) => {
let myData = new User(req.body);
myData.save()
.then(item => {
res.send("Вы успешно зарегистрировались, перенаправление...");
$window.location.href = '/CA.html';
})
.catch(err => {
res.status(400).send("Что-то пошло не так");
});
});
app.listen(port, () => {
console.log("Server listening on port " + port);
});
You can use it in your end-point like this;
app.get('/stackoverflow', (req, res) => {
// Redirect goes to stackoverflow
res.redirect('https://stackoverflow.com/');
})

Cannot read fetch data on express server

On the client side, I have an application based on threejs an d javascript. I want to send data to the server written in express using fetch. Unfortunately, the server does not receive the data and the browser also gives an error:
Uncaught (in promise) TypeError: NetworkError when attempting to fetch resource.
Application:
this.username = prompt("Username:");
const body = JSON.stringify({ username: this.username });
fetch("http://localhost:3000/addUser", { method: "POST", body })
.then((response) => response.json())
.then(
(data) => (
console.log(data), (this.aktualny_album_piosenki = data.files)
)
);
Server:
var express = require("express")
var app = express()
const PORT = 3000;
var path = require("path");
app.use(express.static('dist'));
var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var cors = require('cors');
app.use(cors());
app.post("/addUser", function (req, res) {
console.log(req.body)
})
I might be wrong but maybe try... (very bottom of your main server file)
app.listen((PORT) => {
console.log(`app is listening on port ${PORT}`);
})
is required maybe? I have this chunk of code in every project of my own so maybe that could fix the server not recognizing the api request
express documentation on app listen
heres what I use typically... this is a boilerplate for every one of my projects
const express = require("express");
const app = express();
const connectDB = require("./config/db.js");
const router = express.Router();
const config = require("config");
// init middleware
const bodyParser = require('body-parser');
const cors = require("cors");
const mongoDB = require("./config/db.js");
const path = require("path");
const http = require("http");
const server = http.createServer(app);
const io = require('socket.io')(server, {
cors: {
origin: '*',
}
});
const xss = require('xss-clean');
const helmet = require("helmet");
const mongoSanitize = require('express-mongo-sanitize');
const rateLimit = require("express-rate-limit");
const PORT = process.env.PORT || 5000;
mongoDB();
app.options('*', cors());
app.use('*', cors());
app.use(cors());
const limitSize = (fn) => {
return (req, res, next) => {
if (req.path === '/upload/profile/pic/video') {
fn(req, res, next);
} else {
next();
}
}
}
const limiter = rateLimit({
max: 100,// max requests
windowMs: 60 * 60 * 1000 * 1000, // remove the last 1000 for production
message: 'Too many requests' // message to send
});
app.use(xss());
app.use(helmet());
app.use(mongoSanitize());
app.use(limiter);
// app.use routes go here... e.g. app.use("/login", require("./routes/file.js");
app.get('*', function(req, res) {
res.sendFile(__dirname, './client/public/index.html')
})
app.get('*', cors(), function(_, res) {
res.sendFile(__dirname, './client/build/index.html'), function(err) {
if (err) {
res.status(500).send(err)
};
};
});
app.get('/*', cors(), function(_, res) {
res.sendFile(__dirname, './client/build/index.html'), function(err) {
if (err) {
res.status(500).send(err)
};
};
});
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", '*');
res.header("Access-Control-Allow-Credentials", true);
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header("Access-Control-Allow-Headers", 'Origin,X-Requested-With,Content-Type,Accept,content-type,application/json');
next();
});
if (process.env.NODE_ENV === "production") {
// Express will serve up production files
app.use(express.static("client/build"));
// serve up index.html file if it doenst recognize the route
app.get('*', cors(), function(_, res) {
res.sendFile(__dirname, './client/build/index.html'), function(err) {
if (err) {
res.status(500).send(err)
}
}
})
app.get('/*', cors(), function(_, res) {
res.sendFile(path.join(__dirname, './client/build/index.html'), function(err) {
if (err) {
res.status(500).send(err)
}
})
})
};
io.on("connection", socket => {
console.log("New client connected");
socket.on("disconnect", () => console.log("Client disconnected"));
});
server.listen(PORT, () => {
console.log(`Server listening on port ${PORT}!`);
});
client-side fetch request looks good to me its prob a server/express.JS thing but like i said i may be wrong but worth trying

Trying to findById but server is not return proper status response

Attempting to use Axios.get method to get ':id'
S̶e̶r̶v̶e̶r̶ ̶i̶s̶ ̶r̶e̶s̶p̶o̶n̶d̶i̶n̶g̶ ̶w̶i̶t̶h̶ ̶a̶ ̶4̶0̶4̶
Currently I am unable to set the state of the component. I get an empty object
I've tried adjusting the controller parameters but cannot seem to figure it out
loadProfile() {
axios.get('http://localhost:3000/api/companies/' + this.props.match.params.id)
.then(res => {
if (!res) {
console.log("404 error, axios cannot get response");
} else {
console.log(res.data);
this.setState({ company: res.data });
}
});
express api route
companyRoutes.route('/:id').get(company_controller.company_id_get);
express controller
exports.company_id_get = (req, res) => {
const id = req.params.id;
Company.findById( id, (company, err) => {
if(err) {
console.log("404 error", err);
}
else {
res.json(company);
}
})
}
Server Side Code
'use strict';
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const cors = require('cors')
const passport = require('passport');
const app = express();
const users = require('./routes/api/users');
const companyRoute = require('./routes/api/companies');
app.use(express.static("static"));
//Bodyparser middleware
app.use(cors());
app.use(
bodyParser.urlencoded({
extended: false
})
);
app.use(bodyParser.json());
// DB configuration
const db = require("./config.scripts/mongoKey").mongoURI;
// Connect to MonngoDB
mongoose.connect(
db, { useNewUrlParser: true }
)
.then((db) => console.log('MongoDB succesfully connected'))
.catch(err => console.log(err));
//Passport middleware
app.use(passport.initialize());
//Passport config
require('./config.scripts/passport.js')(passport);
//Routes
app.use('/api/users', users);
app.use('/api/companies', companyRoute);
//Redirect any server request back to index.html: To deal with CRS
app.get('/', function(req, res, next){
res.sendFile(path.join(__dirname, '../client', 'index.html'));
})
//Hostname and Port
//const hostname = '127.0.0.1';
const port = 3000;
app.listen(port, () => {
console.log(`Backend server is running at http://localhost:${port}/`);
});
An error that is showing up in the console/network and postman. It looks like the http.get request is being stalled
Seems you forgot a / in your route http:/localhost:3000/api/companies/.... Change it to http://... and that should fix your issue.

Categories

Resources