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

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

Related

access localhost with smartphone and get no response from the server

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

Insomnia Client only return `Server is up and running.`

I have a simple API server running on Node.js/Express like below:
server.js
const express = require('express');
const cors = require('cors');
const app = express();
var corsOptions = {
origin: 'https://localhost:8081',
}
// middlewares
app.use(cors(corsOptions));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// testing api
app.get('/', (req, res) => {
res.json({message: 'hello from API'})
})
const PORT = process.env.PORT || 8080;
// server
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
It works normally both in the browser and Postman.
Browser
Postman
But when I test it on Insomnia it always Server is up and running.
I've downloaded the newest version and reinstalling using it, but it's still not working as expected and keeps returning the Server is up and running. message.
Did I miss something or there is a configuration to resolve this problem? Thanks

Alwaysdata node.js deployment

I have a following http service in js:
const express = require('express')
const {Client} = require('pg')
var cors = require('cors')
bodyParser = require('body-parser');
port = 8100
const app = express()
const client = new Client({
// censored database connection credentials
})
client.connect()
app.use(bodyParser.json());
app.use(cors())
app.use(bodyParser.urlencoded({extended: true}));
app.post('/user', function(req, res){
console.log(req.body)
var sql = `INSERT INTO "public"."Users" VALUES ('${req.body.Name}','${req.body.Password}','${req.body.Question}','${req.body.Answer}')`
client.query(sql, function(err){
console.log(err)
})
res.send();
})
app.listen(port, () => {
console.log('Server started: ' + port)
})
I upload it on alwaysdata in the following way:
upload form
I get connections timeouts when trying to connect to the hosted server.
What is missing?

post request 404 NOT FOUND after hosting website

So I just hosted a website with Network Solutions and when I try to use the contact form on the site, a 404 error appears. I am aware that something is not configured correctly. What do I need to change in my code? I use Node.js and React.
Error: POST http://www.example.com/api/contact 404 (Not Found)
Port 80 doesn't work...
My index.js file:
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const { contact } = require('./contact');
const app = express();
app.use(express.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(cors());
if (process.env.NODE_ENV === 'production') {
app.use(express.static('client/build'));
const path = require('path');
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'));
});
}
app.post('/api/contact', contact);
const PORT = process.env.PORT || 3001;
app.listen(PORT, () => {
console.log(`Server listening on port ${PORT}`);
});
Do I need to change the PORT code to something else?
I am not aware of how Network Solutions works but the problem is most probably is your port. Check out what is the process.env.PORT (from node console.log) and if it is in 3001 port make sure that port is accessible and not blocked by firewall.

Heroku failed to inject port number to process.env.PORT

I'm deploying my server to Heroku, but for some reason the network shows it keeps making request still to the localhost, instead of dynamically injecting a port number to process.env.PORT
chrome console error message
This is the setup of my server.
require('dotenv').config();
const express = require("express");
const graphqlHTTP = require("express-graphql");
const schema = require('./schema/schema');
const mongoose = require('mongoose');
const cors = require('cors');
const bodyParser = require('body-parser');
mongoose.connect(process.env.mongodburi, { useNewUrlParser: true })
mongoose.connection.once('open', ()=>{
console.log('Connected to database');
});
const app = express();
app.use(cors());
app.use(express.static("public"));
app.use('/graphql', bodyParser.json(), graphqlHTTP({
schema,
graphiql: true
}));
app.withCredentials = true;
app.use('/', (req, res) => res.send("Welcome to read my profile"));
const port = process.env.PORT;
app.listen(port, ()=>{
console.log(`Now listening requests on port:${port}`);
})
Use this
app.listen(process.env.PORT || 3000, function(){
console.log("Express server listening on port %d in %s mode", this.address().port, app.settings.env);
});
Or run $ heroku config:set PORT=3333 as mentioned by デビット

Categories