access localhost with smartphone and get no response from the server - javascript

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}`);
});

Related

NodeJS: Cookie is undefined

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

Put request req.body is empty

As all my requests are working fine, I have a problem with the put. req.body stays empty and then gives that error :
errmsg: "'$set' is empty. You must specify a field like so: {$set:
{: ...}}"
PUT :
router.put('/books/:name', (req, res, next) => {
const localdb = db.client.db(process.env.DB_NAME);
const collection = localdb.collection(process.env.COLL_BOOKS);
collection.replaceOne(
{ "name": req.params.name },
{ $set: req.body },
function (err) {
if (err) throw err
res.status(201).send(true);
});
App.js
const express = require('express'),
app = express();
os = require('os');
const bodyParser = require('body-parser');
const cors = require('cors');
const router = require('./router.js')
require('dotenv').config()
app.use(cors());
app.use(bodyParser.json());
app.use('/api/v1', router);
const port = (process.env.PORT || '3001');
let server = app.listen(port, os.hostname(), () => {
let host = server.address().address,
port = server.address().port;
console.log("Example app listening at http://%s:%s", host, port);
});
axios request :
updateItem = newBook => {
Axios.put(process.env.REACT_APP_API_PATH_BOOKS + `${newBook.name}`, newBook)
.then(res => {
this.setState({ newBook: res.data });
this.props.history.push('/admin');
})
.catch(err => console.log(err));
}
I don't understand what I am doing wrong
Make sure you don't have any middlware stripping or incorrectly parsing the body. For instance, you may have a JSON body parser, and not be sending JSON data with JSON application headers.
Can you give a bit of context, in code, for how you are making the put request and also the result of logging the req in a pastebin?

Why can't I access my API on another computer?

I can't access my API/nodejs server [http://10.0.0.14:3000/] on another computer. If I search for [http://10.0.0.14:3000/] in the browser on my local computer the api is running on I get 'test' with statusCode 200 back. But if I try the same on another computer in the same network I get a timeout. Why does this happen?
const express = require('express');
const bodyParser = require('body-parser');
const { parse } = require('querystring');
const HOST = '10.0.0.14';
const PORT = 3000;
var app = express();
app.use(bodyParser.urlencoded({
extended: true
}));
app.listen(PORT, HOST,function() {
console.log("Server is listening on port 3000...");
});
app.use(bodyParser.json());
app.get('/', function(req,res) {
res.header("Access-Control-Allow-Origin", "*");
// let body = req.body;
console.log("GET ", req.body);
res.send("test");
});
if it is windows add a rule to the firewall for incoming data for port 3000

cannot GET / when serving Angular app using express and nodejs

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

Saving data to json using nodejs and cointicker

Im learning nodejs and I'm creating a server to get the price of cryptocurrencies using a npm called Coin-Ticker. I want to use the data I'm getting in an Angular app but it's not displaying the data in the html. This is my code:
server.js
const express = require('express');
const path = require('path');
const http = require('http');
const bodyParser = require('body-parser');
const coinTicker = require('coin-ticker');
const api = require('./server/routes/api');
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'dist')));
app.use('/api', api);
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist/index.html'));
});
const port = process.env.PORT || '3000';
app.set('port', port);
const server = http.createServer(app);
server.listen(port, () => console.log(`API running on localhost:${port}`));
API.JS
const express = require('express');
const router = express.Router();
const coinTicker = require('coin-ticker');
/* GET api listing. */
router.get('/', (req, res) => {
res.send('api works');
});
router.get((req, res) => {
coinTicker('bitfinex', 'BTC_USD')
.then(posts => {
res.status(200).json(posts.data);
})
.catch(error => {
res.status(500).send(error)
});
});
module.exports = router;
Thanks for your help!
It is because coin ticker returns the json in the then so when you are doing res.status(200).json(posts.data); it is returning undefined. just replace that with res.status(200).json(posts) and it should work
Also you can not do router.get((req, res) => {
you need a path before this. I tried this code with
router.get('/convert', (req, res) => { and with the changes above it worked

Categories