Why is "error empty response' after fetch request? - javascript

My project is bundled on webpack. I've a form which post data to other local server, where saving in txt file. All is okay, data saves correctly, but after a few minutes, on client returns alert "net::ERR_EMPTY_RESPONSE" and then the same form values save to file second time. Why is it saves twice? How to fix this problem.
My fetch post request:
fetch("http://localhost:4000/post", {
method: "POST",
headers: {
"Content-Type": "application/json;charset=utf-8"
},
body: JSON.stringify(fragment),
if(err) {
throw err;
}
})
.then(console.log(fragment))
.catch(alert);
My server:
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const fs = require('fs');
const cors = require('cors');
app.get('/', (req, res) => {
res.send('hello')
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors({
allowedOrigins: [
'http://localhost:9000'
]
}));
app.get('/post', (req, res) => {
console.log(req.body)
res.send('post')
})
app.post('/post', (req, res) => {
res = 0;
if (req.body.film.includes('день: Понеділок')) {
fs.appendFile('booking.monday.txt',
`${req.body.name},${req.body.number},${req.body.film}\n`,
function (err) {
if (err) throw err;
console.log('Saved!');
});
}
})

Related

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

UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'title' of undefined

I believe the error is pointing to the router.post("/", .... post below.
I am using JavaScript, express, ejs, mongoDB.
The purpose of this post is to allow you to save a blog post (confusing choice of words I know), which will then redirect you to the main page ("/"). I am fairly new, any help is appreciated!!
const express = require("express");
const Post = require("../models/post");
const router = express.Router();
// app.set("view engine", "ejs");
router.get("/new", (req, res) => {
res.render("posts/new", { post: new Post() });
});
router.get("/:id", async (req, res) => {
const post = await Post.findById(req.params.id);
if (post == null) res.redirect("/");
res.render("posts/show", { post: post });
});
router.post("/", async (req, res) => {
let post = new Post({
title: req.body.title,
description: req.body.description,
link: req.body.link,
});
try {
post = await post.save();
res.redirect(`/posts/${post.id}`);
} catch (error) {
console.log("failure to create new post");
res.render("posts/new", { post: post });
}
});
module.exports = router;
**EDIT #1 - The below code is my server.js file that I believe is relevant to the error **
const express = require("express");
const mongoose = require("mongoose");
const Post = require("./models/post");
const PostModel = require("./models/post");
const postRouter = require("./routes/post");
const app = express();
require("dotenv").config();
app.set("view engine", "ejs");
const connect = () => {
const un = process.env.MONGO_USER;
const pw = process.env.MONGO_PASSWORD;
return mongoose.connect(
`mongodb+srv://${un}:${pw}#personalblog.b6isg.mongodb.net/PersonalBlog?retryWrites=true&w=majority`,
{ useNewUrlParser: true, useUnifiedTopology: true }
);
};
connect().then(async (connection) => {
const createdPost = Post.create();
console.log(createdPost);
console.log(connect());
});
app.get("/", async (req, res) => {
const post = await Post.find().sort({ createdAt: "desc" });
res.render("posts/index", { post: post });
});
app.use("/posts", postRouter);
app.use(express.urlencoded({ extended: false }));
app.listen(4000);
The req.body is coming as undefined in your router which is causing this issue.
In your app.js, try adding :
app.use(bodyParser.urlencoded({
extended: true
}))
app.use(bodyParser.json())
and send the request again.
base on your coding, you use body that known as json request
router.post("/", async (req, res) => {
let post = new Post({
title: req.body.title,
description: req.body.description,
link: req.body.link,
});
try {
post = await post.save();
res.redirect(`/posts/${post.id}`);
} catch (error) {
console.log("failure to create new post");
res.render("posts/new", { post: post });
}
});
so in your server js, register middleware for json instead
// urlencoded parsing
app.use(express.urlencoded({ extended: false }));
// json parsing
app.use(express.json());

Importing json file from stackexchange and print using node js (express)

I'm trying to request the json file from stackexchange api and when the server loads save it on the client side so I can manipulate/change it locally.
I tried using this code but page just keep loading and nothing happens.
const express = require('express');
const bodyParser = require('body-parser');
const request = require('request');
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json)
const surl = 'https://api.stackexchange.com/2.2/users/11097431?order=desc&sort=reputation&site=stackoverflow';
app.use('/', (req, res, next) => {
request(surl, (error, response, body) => {
// res.setHeader("Content-Type", "application/json; charset=utf-8");
res.json(body)
console.log('body:', body);
console.log('body:', req.body);
});
});
app.listen(3000, () => { console.log('On port 3000...') });
And if I comment out these two lines in my code below
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json)
It gives this kind of output.
"\u001f�\b��\u0000��8z00\u0000^{4���=�c��\u0000��#c�\u0002\u0000\u0000"
If anyone could give me a start that would be great! Thanks.
The output is gibberish because body is gzip compressed. It's not JSON, not even text:
To return it to browser, the easiest way is using pipe:
const request = require('request');
const surl = 'https://api.stackexchange.com/2.2/users/11097431?order=desc&sort=reputation&site=stackoverflow';
app.use('/', (req, res) => {
request(surl).pipe(res);
});
Or, if you want to manipulate/change the body, gzip: true option can be used:
const request = require('request');
const surl = 'https://api.stackexchange.com/2.2/users/11097431?order=desc&sort=reputation&site=stackoverflow';
app.use('/', (req, res) => {
request({
url: surl,
gzip: true
}, function(error, response, body) {
let bodyObj = JSON.parse(body);
// change bodyObj...
res.json(bodyObj);
});
});

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.

Sending data on server by fetch

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 :(

Categories

Resources