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
Related
///index.js
const functions = require("firebase-functions");
const express = require("express");
const app = express();
const productRouter = require('./routes/productRoutes');
const globalErrorHandler = require('./controllers/errorController');
const AppError = require('./utils/appError');
// Compressing upcompressed files which is been sent to client such text.
if (process.env.NODE_ENV === 'development') {
app.use(morgan('dev'));
}
// app.use(express.static(path.join(__dirname, 'public')));
app.get('/', (req, res) => {
res.send('Hello World')
});
app.get('/homepage', (req, res) => {
res.send('Hello People of God')
});
app.use('/products', productRouter);
// Handing Unhandled Routes
app.all('*', (req, res, next) => {
next(new AppError(`Can't find ${req.originalUrl} on this server!`, 404));
});
app.use(globalErrorHandler);
exports.app = functions.https.onRequest(app);
///productRoutes.js
const express = require('express');
const {
getProduct,
getAllProduct,
} = require('./../controllers/productController');
const router = express.Router();
router
.route('/')
.get(getAllProduct);
router
.route('/:id')
.get(getProduct);
module.exports = router;
///productController.js
const AppError = require('../utils/appError');
const Product = require('../modals/productModels');
const catchAsync = require('../utils/catchAsync');
// GET SINGLE PRODUCT CONTROLLER
exports.getProduct = catchAsync(async (req, res, next) => {
const product = await Product.findById(req.params.id)
.populate('reviews');
if (!product) {
return next(new AppError('No product found with that ID', 404));
}
res.status(200).json({
status: 'success',
data: {
product
}
});
});
// GET ALL PRODUCT CONTROLLER
exports.getAllProduct = catchAsync(async (req, res, next) => {
const products = await Product.find();
res.status(200).json({
status: 'success',
results: products.length,
data: {
products
}
});
});
///server.js
const mongoose = require('mongoose');
const app = require('./index')
const dotenv = require('dotenv');
// CONNECTING TO MONGODB SERVER
dotenv.config({ path: './config.env' })
const DB = process.env.DATABASE.replace('<PASSWORD>', process.env.DATABASE_PASSWORD);
mongoose.connect(DB, {
useNewUrlParser: true,
safe: true,
strict: false,
useUnifiedTopology: true
}).then(con => console.log('DB connection successful'))
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`App running on port ${port}...`);
});
After running function serve on my terminal i can access the two '/' and 'homepage' app.get which return the res "Hello world" and "Hello people of God" but can't access app.use('/products', productRouter). Its does take some time to run and throw an error "{"code":"ECONNRESET"}" please why is this so.
Am expecting to get my list of products from my mongodb data base.
I am trying to build a webchat app using node.js and express. I have a router file and a server file, together with some client files. I would like to emit a join event from the router and processing it on the server so the user can join the room. I did i like this
Server.js
const express = require('express');
const layout = require('express-layout');
const app = express();
var server = require('http').createServer(app);
var io=require('socket.io')(server);
const routes = require('./router')(io);
const bodyParser = require('body-parser');
var fs = require("fs");
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
const middleware = [
layout(),
express.static(path.join(__dirname, 'public')),
bodyParser.urlencoded(),
];
app.use(middleware);
app.use('/', routes);
app.use((req, res, next) => {
res.status(404).send("Sorry can't find that!");
});
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something broke!');
});
io.on('connect', onConnect);
function onConnect(socket) {
var contents = fs.readFileSync("./public/rooms.json");
let rooms = JSON.parse(contents);
socket.emit('parse',rooms);
socket.on('join',function (name, room) {
console.log(name+" "+ room);
socket.join(room);
socket.user=name;
socket.room=room;
})
}
Here I just initialize the io connection together with all the dependencies I use. I use const routes = require('./router')(io); to pass the io variable
router.js
const express = require('express');
const User= require("./public/classes/User");
const router = express.Router();
const {check, validationResult} = require('express-validator');
const {matchedData} = require('express-validator/filter');
var userlist=new Array();
router.get('/', (req, res) => {
res.render('index', {
data: {},
errors: {}
})
});
router.post('/enter', [
check('username')
.isLength({min: 1})
.withMessage('Username is required').trim() //implement personalized check
], (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.render('index', {
data: req.body,
errors: errors.mapped()
})
}
const data = matchedData(req)
handleJoin(data);
});
return router;
//MOVE TO SUPPORT
function find(name) {
return 1;
}
function handleJoin (data){
if(find(data.username)){
const newUser= new User (data.username, data.room,"");
userlist.push(newUser);
io.emit('join',newUser.name,newUser.room);
}
};
};
The console should log the name and the choosen room but it doesn't. How do I process this?
I can't figure out how to query the MySQL database from the promise in my route file. I'm writing a RESTful API to query a MySQL database with GET methods. I'm using Express and Axios for Javascript promises.
I want to get back the list of books from a SQL table and the count of how many listings in the returned JSON.
server.js
const http = require('http');
const app = require('./app');
const port = process.env.PORT || 3000;
const server = http.createServer(app);
server.listen(port);
app.js
const express = require('express');
const app = express();
const morgan = require('morgan');
const bodyParser = require('body-parser');
const mysql = require('mysql');
const bookRoutes = require('./api/routes/books');
const entryRoutes = require('./api/routes/entries');
const connection = mysql.createConnection({
host: 'localhost',
user: 'rlreader',
password: process.env.MYSQL_DB_PW,
database: 'books'
});
app.use(morgan('dev'));
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
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', 'GET');
return res.status(200).json({});
}
next();
});
// Routes which should handle requests
app.use('/books', bookRoutes);
app.use('/entries', entryRoutes);
app.use((req, res, next) => { //request, response, 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;
books.js
const express = require('express');
const router = express.Router();
const axios = require('axios');
//do I import something for mysql here?
router.get('/', (req, res, next) => {
axios.get('/').then(docs => {
res.status(200).json({
"hello": "hi" //want to query MySQL database here
})
}).catch(err => {
res.status(500).json({
error: err
});
})
});
module.exports = router;
Any help would be appreciated. For starters, how do I get const connection from app.js to books.js?
I moved the code connecting to the MySQL database to a separate file and included that:
const con = require('../../db');
Next, I had to properly return the response:
router.get('/', (req, res, next) => {
let responseData = axios.get('/').then(docs => {
const sql = "SELECT title, id FROM books";
con.query(sql, function (err, result) {
if (err) {
console.log("error happened");
}
return res.status(200).json(result);
});
}).catch(err => {
res.status(500).json({
error: err
});
});
});
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.
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 :(