hello im using express for server everything is working find but i am not receiving my data from post method.Iam using body-parser too
const express = require("express")
const app = express()
var bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.post("/signup", (req,res)=>{
var data = req.body
res.send(req.body)
})
Here is a 100% working code. If it doesn’t work, then tell me how do you make a POST request?
const express = require("express")
const app = express()
const bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.post("/signup", (req, res) => {
var data = req.body
console.log(data)
res.send(req.body)
})
app.listen(3000)
Front-end:
axios.post('http://localhost:3000/signup', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
Related
Im new in express.js so i would like to know why when I'm sending a data to client the data is showing in the browser but I'd like to send it in preview please can you take a look what I do wrong?
app.use(cors())
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.get('/getProducts', (req,res) => {
const obj = {
data: 'jojo'
};
res.set('Content-Type','application/json');
res.json(obj);
});
first you need install dependencies like body-parse cors, then you need listen port like this
const express = require('express')
const cors = require('cors')
const bodyParser = require('body-parser')
const app = express()
app.use(cors())
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.get('/getProducts', (req, res) => {
const obj = {
data: 'jojo'
};
res.set('Content-Type', 'application/json');
res.json(obj);
});
app.listen(3000)
const express = require("express");
const app = express();
var fetchUrl = require("fetch").fetchUrl;
var wordsCounter = require("word-counting");
const bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
app.post("/game", (req, res) => {
const data= req.body;
console.log(data.website)
fetchUrl(`${data.website}`, (error, meta, body) =>{
let answer = wordsCounter(body.toString(), { isHtml: true }).wordsCount;
console.log(answer)
res.send({answer});
});
});
app.listen(6000, () => {
console.log("Server in action!");
});
I was trying to convert the HTML body to string so as to count the number of words but it's showing TypeError, Why is it so?
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());
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 :(