I'm trying to make a simple GET request to my localhost:8080.
When I make the GET request with Postman, I set a simple cookie. Now, in the main file, I've:
var express = require('express');
var app = express();
const cookieParser = require('cookie-parser');
app.use(cookieParser());
const app_router = require('./routes/router');
app.use("/api", app_router);
app.use(express.static('public'));
app.listen(8080, function () {
console.log('Outdoor Localization GNSS middleware.');
});
In routes/router.js I have:
var express = require('express')
const router = express.Router();
const axios = require('axios');
const url = 'http://10.10.0.145:80/api'
router.use(express.json());
router.get('/*', function (request, response) {
console.log(request.Cookie)
axios
.get(request_url)
.then(res => {
console.log(request.Cookie)
})
.catch(error => {
console.error(error)
})
});
The problem is that request.Cookie always return undefined...why is this happening?
you should be accessing the property request.cookies instead of request.Cookie
Related
I am trying to create a REST API using Express JS.
console.log(req.body) gives undefined as output,
this is my code in routes.js page
const express = require('express');
const router = express.Router();
router.post('/post',async (req,res) => {
console.log("inside post router");
console.log(req.body);
const data = new Model({
name: req.body.name,
age: req.body.age
})
try {
const dataToSave = await data.save();
res.status(200).json(dataToSave)
}
catch(error) {
res.status(400).json({message:error.message})
}
})
This is the code in index.js file
const express = require('express');
const mongoose = require('mongoose');
const routes = require('./Routes/routes');
const app = express();
app.use('/api',routes);
User middlewares ,for parsing the post body in your index.js file
const express = require('express');
const mongoose = require('mongoose');
const routes = require('./Routes/routes');
const app = express();
app.use(express.json()) ; //parsing application/json
app.use(express.urlencoded({extended: false}) ;
app.use('/api',routes);
Make sure to use them ,before you configure your routes
See reference
website works via localhost on pc
access with smartphone to localhost via ip too (I receive html, css and js for client)
when I click the button, a "hi" is also added but function "search()" is not executed
but when I enter the url http://localhost:3000/users I get the "hi1"
What do i have to do to make this work?
Client Side
const button = document.querySelector("button");
button.addEventListener("click", () => {
document.getElementById("imageDiv").innerHTML = "Hi";//this work
search();//this not work
});
async function search(){
await fetch("http://localhost:3000/users")
.then(response => response.json())
.then(response => {
var image;
image = JSON.parse(JSON.stringify(Object.assign({},response)));
document.getElementById("imageDiv").innerHTML = response;
})};
Server Side
const express = require('express');
const bodyParser = require('body-parser');
const path = require("path"); // window or mac
const cors = require('cors');
const app = express();
const port = 3000;
//var word = "";
//const router = express.Router();
// configure CORS to avoid CORS errors
app.use(cors());
// configure body parser so we can read req.body
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static('./client'));
app.get('/', (req, res) => {
res.sendFile("./index.html");
});
app.get("/users", (req, res) => {
datafiles = ["hi1"];
res.json(datafiles);
res.status(200);
});
app.listen(port, () => {
console.log(`Server listening on http://localhost:${port}`);
});
I want to send some data to my MongoDB database, but in router.post my req.body is empty, if I use stuff that I put in my send function in User(req.body) instead of req.body data will be send to my MongoDB database correctly.
This is my router that I use, router.get work fine, it return database tables correctly on /api page:
const router = require("express").Router();
const User = require("./model/models");
const parser = require("body-parser").json();
router.get("/", async (req, res) => {
const data = await User.find({});
res.json(data);
});
router.post("/",parser,async (req, res) => {
console.log('1')
console.log(req.body)
console.log('2')
parser.v
await User(req.body).save();
res.json({"msg": "ok"});
});
module.exports = router
This is my index.js file code:
const bodyParser = require('body-parser');
const express = require('express');
const app = express();
const parser = require("body-parser").json();
var path = require('path');
app.use(express.urlencoded(true));
app.use(express.json());
app.use(parser);
app.use('/',require("./routes/routes"))
app.use(express.static(__dirname +'/public'))
app.use("/api", require('./data/api'))
app.listen(5000,function(){
console.log('server is alive')
})
This is function that what I use to send data:
const btn1 = document.getElementById('btnEnter')
let Login = "123"
btn1.addEventListener('click' ,e=>{
send({newsTxT : "someTextHere",newsZag:"someZag",author:"SomeAuthor"})
})
const send = async(body) => {
let res = await fetch("/api", {
method: "post",
header: {
"Content-Type": "application/json",
"Accept": "application/json"
},
body: JSON.stringify(body)
});
let data = await res.json();
console.log(data)
}
The only weird thing I see is that you are using a json body-parser and also the express.json() both technically do the same, but body-parser is deprecated so it might be causing a bug.
Also you don't have to import it again in the routes, placing app.use(express.json()) at index.js will make it work for all endpoints/routes.
See how this refactor goes:
const router = require('express').Router()
const User = require('./model/models')
router.get('/', async (req, res) => {
const data = await User.find({})
res.json(data)
})
router.post('/', async (req, res) => {
console.log('1')
console.log(req.body)
console.log('2')
await User(req.body).save()
res.json({ 'msg': 'ok' })
})
module.exports = router
index.js
const express = require('express')
const app = express()
var path = require('path')
app.use(express.urlencoded(true))
app.use(express.json())
app.use('/', require('./routes/routes'))
app.use(express.static(__dirname + '/public'))
app.use('/api', require('./data/api'))
app.listen(5000, function () {
console.log('server is alive')
})
The following worked fine:
const express = require("express")
const app = express()
const router = express.Router()
router.use(express.json())
app.use(router)
router.post('/api/user', function(req, res) {
// ...
}
I see the difference may be using the: app.use(router)
Note that in the above code the statement:
router.use(express.json())
can be replaced with (using the body-parser):
const bodyParser = require('body-parser')
router.use(bodyParser.json())
This worked fine with express version 4.17.1, body-parser version 1.19.0 and NodeJS version 12.18.3
I'm getting "Cannot GET /speakers" error on my browser when I am trying to access http://localhost:3000/speakers from the following code:
My Server.js File
const express = require('express')
const path = require('path')
const routes = require('./routes')
const app = express()
const port = 3000
app.set('view engine','ejs')
app.set('views', path.join(__dirname,'./views'))
app.use(express.static(path.join(__dirname,'./static')))
app.use('/', routes())
app.listen(port,()=>{
console.log(`Express server listening on port ${port}!`)
})
My Script.js File
This is my server.js file where I've declared various variables
const express = require('express')
const router = express.Router()
module.exports = () =>{
router.get('/',(request, response) =>{
return response.send('Speakers List')
})
router.get('/:shortname',(request, response) =>{
return response.send(`Detail page of {request.params.shortname}`)
})
return router;
}
My index.js file
const express = require('express')
const speakersRoute = require('./speakers')
const feedbackRoute = require('./feedback')
const router = express.Router()
module.exports = () =>{
router.get('/',(request, response) =>{
response.render('pages/index',{ pageTitle: 'Welcome'})
})
router.use('./speakers', speakersRoute())
router.use('./feedback', feedbackRoute())
return router
}
Can anyone help me on this?
Have you try change './speaker' to '/speaker' ?
// router.use('./speakers', speakersRoute())
router.use('/speakers', speakersRoute())
I am trying to serve an angular app using nodejs. But i get this error
"Cannot GET /" in the body of the page. I tried a number of things but still this does not work. do you folks have any suggestion?
const express = require('express')
const app = express()
var cors = require('cors')
const bodyParser = require('body-parser')
const fileUpload = require('express-fileupload')
const couchDb = require('./modules/couchDb')
const db = couchDb.db
const schedules = require('./modules/schedules')
const stations = require('./modules/stations')
const testConfigs = require('./modules/testConfigs')
app.use(cors())
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}))
app.use(fileUpload())
app.listen(5000, () => console.log('Listening on port 5000'))
////////////////////////////////////////
// View
////////////////////////////////////////
const viewOptions = { include_docs: true }
app.route('/api/schedules').get((req, res) => {
couchDb.getType('schedule', viewOptions).then(docs => {
res.send(docs)
}).catch(err => {
console.log(err)
res.send({})
})
})
app.route('/api/stations').get((req, res) => {
couchDb.getType('station', viewOptions).then(docs => {
res.send(docs)
}).catch(err => {
console.log(err)
res.send({})
})
})
app.route('/api/tests').get((req, res) => {
couchDb.getType('testConfig', viewOptions).then(docs => {
res.send(docs)
}).catch(err => {
console.log(err)
res.send({})
})
})
you are missing your routes e.g
app.get('/', function (req, res) {
res.send('hello world')
})
or you need to include your all routes through middle ware.
You are getting that error because you are not declaring any endpoints or telling the server to serve anything. It is listening on port 5000, but no responses to any urls have been defined. Here is a piece of example code that will resolve your issue.
const express = require('express')
const app = express()
var cors = require('cors')
const bodyParser = require('body-parser')
const fileUpload = require('express-fileupload')
app.use(cors())
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}))
app.use(fileUpload())
// This block will make it so that every path on port 5000 responds with "Hello, World!"
app.get('*', (req, res) => {
res.status(200).send("Hello, World!");
});
app.listen(5000, () => console.log('Listening on port 5000'))
This will make it respond with basic text, if you want to serve an angular application, you will need to look into serving static content from express: https://expressjs.com/en/starter/static-files.html
You have to use a routing middleware and map your modules to the required modules.Also make sure your modules are mounted in router instance.
Something like
const express = require('express')
const app = express()
var cors = require('cors')
const bodyParser = require('body-parser')
const fileUpload = require('express-fileupload')
const couchDb = require('./modules/couchDb')
const db = couchDb.db
const schedules = require('./modules/schedules')
const stations = require('./modules/stations')
const testConfigs = require('./modules/testConfigs')
app.use(cors())
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}))
app.use(fileUpload())
//All requests with /schedules will go to './modules/schedules'
app.use('/schedules', schedules);
app.use('/stations', stations);
app.listen(5000, () => console.log('Listening on port 5000'))
your ./modules/station should look like
var express = require('express')
var router = express.Router()
router.get('/', function (req, res) {
res.send('You are in /station')
})
router.get('/new', function (req, res) {
res.send('You are in /station/new')
})
module.exports = router
For more : https://expressjs.com/en/guide/routing.html