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.
Related
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
So I am coding this web on Heroku and I try to integrate a socket into the setup. But the problem is that I cannot make both my Heroku app and socket.io server listen to the same port.
The default port for Heroku seems to be 5000 and for socket.io seems to be 3000.
If I try to change either of the ports to the same as the other, then the EADDRINUSE error pops up.
However, if I don't, then the two processes seems to operate separately
when I run npm start, then the terminal says
Listening on 5000
listening on xoxo 3000
And when I turned on to localhost:3000 it actually works ( the socket.io ), but on localhost:5000 it obviously doesn't. As a matter of fact, it also doesn't work on the Website that Heroku generated for me (only the localhost:5000 showed up)
The code lines below are from my index.js file.
How could I fix this? Thank you in advance.
const express = require('express');
const app = express();
const path = require('path')
const http = require('http');
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);
const PORT = process.env.PORT || 5000;
const INDEX = '/index.ejs'
app.listen(PORT, () => console.log(`Listening on ${ PORT }`))
app.use(express.static(path.join(__dirname, 'public')));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.get('/', (req, res) => res.render('index'));
io.on('connection', (socket) => {
socket.on('playerEvent', (msg) => {
console.log(msg);
});
console.log('a user connected');
socket.on('disconnect', () => {
console.log('user disconnected');
});
socket.broadcast.emit('hi');
});
server.listen(3000, () => {
console.log('listening on xoxo 3000');
});
//socket.on('playerEvent', function(msg){
// console.log(msg);
//});
I have been developing a node backend, react front end web app for a couple months. It has working just fine when I started the server via nodemon and the front end with npm start. But now that I am getting ready to host an alpha version and ran 'npm run build' I've been running into issues.
It seems to be stemming from the interaction of accessing the app from the server's port and react-router. I added a catch-all endpoint app.get('/*'...) to my server to allow the react-router to work. So now when the front requests data, the response is HTML not the array I want.
I feel like there is a simple solution to this, but I just don't see it yet. I looked into using HashRouter instead of BrowserRouter, but unfortunately I can't use that because I am using MSAL Active Directory for login.
server/index.js
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors')
require('dotenv').config();
const massive = require('massive');
const session = require("express-session");
const morgan = require('morgan');
const path = require('path');
const ctrl = require(`./controllers/controller.js`);
//Middleware
const app = express();
app.use(bodyParser.json());
app.use(cors());
app.use(express.static(__dirname + './../build'));
app.use(morgan('dev'));
//Connection to Azure DB
massive(process.env.CONNECTION_STRING)
.then(db => {
console.log('Connected to Azure PostgreSQL Database')
app.set('db', db)
}).catch(err=>console.log(err))
app.use(session({
secret: process.env.SESSION_SECRET,
cookie: { maxAge: 60000 },
resave: false,
saveUninitialized: true
}));
//Endpoints
app.get('/*', function(req, res) {
res.sendFile(path.join(__dirname, './../build/index.html'), function(err) {
if (err) {
res.status(500).send(err)
}
})
})
app.get('/getallemployees/', ctrl.getAllEmployees)
app.listen(8080, () => console.log(`Listening on ${8080}`));
Put that catch-all endpoint after all the others that return data.
//Endpoints
app.get('/getallemployees/', ctrl.getAllEmployees)
app.get('/*', function(req, res) {
res.sendFile(path.join(__dirname, './../build/index.html'), function(err) {
if (err) {
res.status(500).send(err)
}
})
})
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
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 デビット