My app works locally but once deployed to Heroku, every page works except the home page where the json data is displayed instead of the UI. On this page, I am listing the posts from the db so the posts in the db are being displayed as json data.
I tried prepending post routes with '/post' to stop api returning html on '/' route but now I'm getting this problem. Whatever I change, it just keeps switching between these two issues - either json data is displayed or index.html is returned instead of data.
How can I fix this?
Thanks!
The route for that specific page (this is the first route):
<Route path="/posts/" exact component={Home} />
server.js
// imports
...
require("dotenv").config();
// import routes
const authRoutes = require("./routes/auth");
const userRoutes = require("./routes/user");
const postRoutes = require("./routes/posts");
// app
const app = express();
// connect db
const url = process.env.MONGODB_URI
mongoose.connect(url, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true,
useFindAndModify: false,
});
mongoose.connection
.once("open", function () {
console.log("DB Connected!");
})
.on("error", function (error) {
console.log("Error is: ", error);
});
// middlewares
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", '*');
res.header("Access-Control-Allow-Credentials", true);
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header("Access-Control-Allow-Headers", 'Origin,X-Requested-With,Content-Type,Accept,content-type,application/json');
next();
});
//middleware
...
// routes middleware
// app.use(express.static(path.join(__dirname, './client/build')))
if (process.env.NODE_ENV === "production") {
app.use(express.static("client/build"));
}
app.use(authRoutes);
app.use(userRoutes);
app.use('/post', postRoutes);
app.get("/*", function (req, res) {
res.sendFile(path.join(__dirname, "./client/build/index.html"));
});
const port = process.env.PORT || 80;
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
ListPosts.js
// imports
...
import { API } from "../config";
class ListPosts extends React.Component {
state = {
title: "",
body: "",
date: "",
posts: [],
};
componentDidMount = () => {
this.getPosts();
};
getPosts = () => {
axios
.get(`${API}/post/`)
.then((response) => {
const posts = response.data;
this.setState({ posts });
})
.catch((error) => {
console.log(error);
});
};
displayPosts = (posts) => {
if (!posts.length) return null;
return posts.map((post, index) => (
...
));
};
render() {
return <div>{this.displayPosts(this.state.posts)}</div>;
}
}
export default ListPosts;
list route/controller
router.get("/", list);
exports.list = (req, res) => {
const sort = { title: 1 };
Post.find()
.sort(sort)
.then((posts) => res.json(posts))
.catch((err) => res.status(400).json("Error: " + err));
};
Related
When ever I run my server locally it works perfectly
But once I upload it to vercel I get errors like polling-xhr.js:202 GET https://giphy-chat-server.vercel.app/socket.io/?EIO=4&transport=polling&t=NQ03j3c&sid=H_PHDh9-4UKRVGTVAAAC 400
And WebSocket connection to 'wss://giphy-chat-server.vercel.app/socket.io/?EIO=4&transport=websocket&sid=k-Sex1ZKmrQQFoSKAAAA' failed: Error during WebSocket handshake: Unexpected response code: 400
I have tried so many solutions but none is working... I can't just figure out the problem. I would be glad if Its answered. Thank you
const express = require("express");
const app = express();
const http = require("http");
const path = require("path");
var server = http.createServer(app);
const io = require("socket.io")(server, {
cors: {
origin: "*",
credentials: true,
methods: ["GET", "POST"],
},
});
const { MONGODB_URI } = require("./config");
const port = process.env.PORT || 8000;
const Message = require("./message_model");
const mongoose = require("mongoose");
mongoose
.connect(MONGODB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
})
.then((result) => {
server.listen(port, () => {
console.log(`Listening on port ${port}...`);
});
})
.catch((err) => {
console.log(err);
});
app.use(express.static(path.join(__dirname, "..", "client", "build")));
const users = [];
io.on("connection", (socket) => {
users.push({ id: socket.id });
io.emit("users", { users: users });
Message.find()
.sort({ createdAt: -1 })
.limit(10)
.exec((err, messages) => {
if (err) return console.error(err);
socket.emit("init", messages);
});
socket.on("message", (msg) => {
const message = new Message({
content: msg.content,
name: msg.name,
});
message.save((err) => {
if (err) return console.error(err);
});
socket.broadcast.emit("push", msg);
});
socket.on("disconnect", (reason) => {
let index = -1;
for (let i = 0; i < users.length; i++) {
const user = users[i];
if (user.id === socket.id) {
index = i;
}
}
if (index !== -1) {
users.splice(index, 1);
}
io.emit("users", { users: users });
});
});
app.get("/", (req, res) => {
res.send("Giphy Chat Server is running successfully");
});
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header("Access-Control-Allow-Headers", "Content-Type");
res.header("Access-Control-Allow-Methods", "PUT, GET, POST, DELETE, OPTIONS");
next();
});
I think this will be due to Vercel's serverless functions having a maximum execution timeout, so they can't maintain a websocket connection. In order to use Websockets with Vercel you'll need to use a third party service to handle your websocket connections for you. Something like Ably or Pusher, or PubNub.
I just wrote up a demo of next + ably if it would be helpful - https://github.com/ably-labs/NextJS-chat-app
I've created a MERN application and I'm trying to deploy it to heroku. When I try to build the application and test it with 'heroku local', everything seems to work, the local server starts and the database connects, however the initial page '/' is a blank screen. But if I type a different route like '/rankings/', it will work.
Below is a copy of my express server
// all imports below
const express = require("express");
const mongoose = require('mongoose');
const fileUpload = require("express-fileupload")
const p4pBoxingRankings = require("./p4pBoxingRankings")
const divisionalRankings = require("./divisionalRankings.js")
const ufcP4pRankings = require("./ufcRankings.js")
const ufcDivisionalRankings = require("./ufcDivisionalRankings.js")
let bodyParser = require('body-parser');
let cors = require('cors');
const app = express();
const path = require('path');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(fileUpload());
app.use(cors());
app.use(express.static('public'));
app.set('port', (process.env.PORT || 8080));
// code to connect datbase below
const URI = process.env.MONGODB_URI || "mongodb+srv://skunk_hunnt:P#cquiaop4p224#cluster0.4cqzd.mongodb.net/Fight_Auction?retryWrites=true&w=majority"
mongoose.connect(URI, { useNewUrlParser: true })
.then(() => {
console.log('Database connected...')
}).catch((err) => {
console.log(err);
})
// code to stringify items below
const ItemSchema = new mongoose.Schema({
itemDescription: { type: String },
askingPrice: { type: String },
itemDetails: { type: String },
pictures: {type: String}
});
const fightItem = mongoose.model('Item', ItemSchema);
// all axios requests below
app.get("/items", function(req, res){
//make a DB query and send back all the items
fightItem.find({},(err, data)=>{
res.send(data)
})
})
app.get("/rankings", async(req, res) => {
res.send(p4pBoxingRankings);
})
app.get("/rankings/divisions", async(req, res) => {
res.send(divisionalRankings);
})
app.get("/rankings/divisions/ufcp4p", async(req, res) => {
res.send(ufcP4pRankings);
})
app.get("/rankings/divisions/ufcp4p/ufcdivisions", async(req, res) => {
res.send(ufcDivisionalRankings);
})
app.post("/items", function(req, res){
let item = new fightItem();
item.itemDescription = req.body.item.itemDescription
item.askingPrice = req.body.item.askingPrice
item.itemDetails = req.body.item.itemDetails
item.pictures = req.body.item.pictures
item.save((err,res)=>{
})
});
app.post('/upload', (req, res) => {
if (req.files === null) {
return res.status(400).json({ msg: 'No file uploaded' });
}
const file = req.files.file;
file.mv(`${__dirname}/public/${file.name}`, err => {
if (err) {
console.error(err);
return res.status(500).send(err);
}
res.json({ fileName: file.name, filePath: `/public/${file.name}` });
});
});
// if (process.env.NODE_ENV === 'production') {
// // Serve any static files
// app.use(express.static(path.join(__dirname, 'build')));
// // Handle React routing, return all requests to React app
// app.get('*', function(req, res) {
// res.sendFile(path.join(__dirname, '/build/index.html'));
// });
// }
app.use("", express.static(path.join(__dirname, 'build')));
// Handle React routing, return all requests to React app
app.get('*', function(req, res) {
res.sendFile(path.join(__dirname, '/build/index.html'));
});
app.listen(app.get('port'), function() {
console.log('Server started on port '+app.get('port'));
});
Here is my react router.
import React from "react";
import { BrowserRouter, Route, Switch, } from "react-router-dom";
import BrowseItemsPage from "../components/BrowseItemsPage.jsx";
import HomePage from "../components/HomePage.jsx";
import NewsAndRankings from "../components/NewsAndRankingsPage.jsx";
import NotFoundPage from "../components/NotFoundPage.jsx";
import SellItemPage from "../components/SellItemPage.jsx";
const AppRouter = () => (
<BrowserRouter>
<div>
<Switch>
<Route path="/" component={HomePage} exact={true}/>
<Route path="/browse-items" component={BrowseItemsPage}/>
<Route path="/sell-items" component={SellItemPage}/>
<Route path="/rankings" component={NewsAndRankings}/>
<Route component={NotFoundPage}/>
</Switch>
</div>
</BrowserRouter>
);
export default AppRouter;茀
I've tried numerous configurations and been pulling my hair out for a couple days now. However no matter what I do when I try to hit /users/uploadmulter I get an authorized error.
On mongoDB atlas I've tried creating a new collection.
Moving the route declaration in my users file (that way I know it's not an express config issue as other operations work i.e. make a user, get new password etc.)
Anyway, here is my React component:
import { useState, useEffect } from 'react';
import { Card, Icon, Image, Segment, Form } from 'semantic-ui-react';
import axios from 'axios';
function ImageUploader() {
var [defaultImage, setDefaultImage] = useState(
require('../../assets/images/placeholder.jpg')
);
var [userAvatar, setUserAvatar] = useState(defaultImage);
useEffect(() => {
setUserAvatar(userAvatar);
}, [userAvatar]);
function fileUploader(e) {
console.log('event fileUploader ', e);
var imageFormObj = new FormData();
console.log('e.target.files[0] ', e.target.files[0]);
imageFormObj.append('avatar', 'multer-image-' + Date.now());
imageFormObj.append('imageData', e.target.files[0]);
setUserAvatar(URL.createObjectURL(e.target.files[0]));
console.log('userAvatar ', userAvatar);
console.log('imageFormObj ', imageFormObj);
axios
.post('http://localhost:8016/users/uploadmulter', imageFormObj)
.then(data => {
if (data.data.success) {
alert('Image has been successfully uploaded using multer');
}
})
.catch(err => {
alert('Error while uploading image using multer');
});
}
return (
<>
<Segment>
<Card fluid>
<Image src={userAvatar} alt="upload-image" />
<Segment>
<Form encType="multipart/form-data">
<Form.Field>
<input
placeholder="Name of image"
className="process__upload-btn"
type="file"
name="avatar"
content="Edit your Avatar!"
onChange={e => fileUploader(e)}
/>
{/* <Button
content="Edit your Avatar!"
labelPosition="left"
icon="file"
onClick={e => fileUploader(e)}
/> */}
</Form.Field>
</Form>
</Segment>
<Card.Content>
<Card.Header>Charly</Card.Header>
<Card.Meta>
<span className="date">Joined in 2015</span>
</Card.Meta>
<Card.Description>Charly</Card.Description>
</Card.Content>
<Card.Content extra>
<a>
<Icon name="user" />
22 Friends
</a>
</Card.Content>
</Card>
</Segment>
</>
);
}
export default ImageUploader;
And this is my route which handles sending the data to MongoDB Atlas:
var router = require('express').Router();
var Image = require('../models/UserImagesSchema');
var multer = require('multer');
var storage = multer.diskStorage({
destination: function(req, file, cb) {
cb(null, './uploads/');
},
filename: function(req, file, cb) {
cb(null, Date.now() + file.originalname);
}
});
var upload = multer({
storage: storage,
limits: {
fileSize: 1024 * 1024 * 5
}
});
/*
stores image in uploads folder
using mulkter and creates a reference to the file
*/
router.post(upload.single('imageData'), (req, res, next) => {
console.log(req.body);
var newImage = new Image({
avatar: {
imageName: req.body.avatar,
imageData: req.file.path
}
});
newImage
.save()
.then(result => {
console.log(result);
res.status(200).json({
success: true,
document: result
});
})
.catch(err => next(err));
});
module.exports = router;
This is my Schema:
var mongoose = require('mongoose');
/* Image Schema for storing images in the mongodb database */
var UserImagesSchema = new mongoose.Schema({
avatar: {
_userId: { type: mongoose.Schema.Types.ObjectId, required: true, ref: 'User' },
imageName: { type: String, default: 'none', required: true },
imageData: {
data: Buffer,
contentType: String
}
}
});
module.exports = mongoose.model('UserImages', UserImagesSchema);
This is the app/server file for express:
var express = require('express');
require('dotenv').config();
var path = require('path');
var morgan = require('morgan');
var cookieParser = require('cookie-parser');
var cors = require('cors');
var nextJS = require('next');
var session = require('express-session');
var MongoStore = require('connect-mongo')(session);
var bodyParser = require('body-parser');
var auth = require('./lib/auth');
var HttpStatus = require('http-status-codes');
var compression = require('compression');
var helmet = require('helmet');
var PORT = process.env.PORT || 8016;
var { isBlockedPage, isInternalUrl } = require('next-server/dist/server/utils');
function NODE_ENVSetter(ENV) {
var environment,
environments = {
production: () => {
environment = process.env.MONGODB_URI;
console.log(`We are currently in the production environment: ${environment}`);
return environment;
},
test: () => {
environment = process.env.TEST_DB_DSN;
console.log(`We are currently in the test environment: ${environment}`);
return environment;
},
default: () => {
environment = process.env.DEVELOPMENT_DB_DSN;
console.log(`We are currently in the development environment: ${environment}`);
return environment;
}
};
(environments[ENV] || environments['default'])();
return environment;
}
var db = NODE_ENVSetter('development');
var mongoose = require('mongoose');
function errorHandler(err, req, res, next) {
// Set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// Log error
console.error(err.stack);
// Render the error page
res.status(err.status || 500);
// Default error message by HTTP code
res.render('error', {
title: HttpStatus.getStatusText(err.status),
message: HttpStatus.getStatusText(err.status)
});
}
function start() {
const dev = process.env.NODE_ENV !== 'production';
const app = nextJS({ dev });
const server = express();
// const proxy = createProxyMiddleware(options);
app
.prepare()
.then(() => {
mongoose.connect(db, { useNewUrlParser: true, useUnifiedTopology: true });
mongoose.Promise = global.Promise;
mongoose.connection
.on('connected', () => {
console.log(`Mongoose connection open on ${db}`);
})
.on('error', err => {
console.log(`Connection error: ${err.message}`);
});
})
.catch(err => {
console.error(err);
});
server.use(
session({
secret: 'very secret 12345',
resave: false,
saveUninitialized: false,
store: new MongoStore({ mongooseConnection: mongoose.connection })
})
);
server.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.header(
'Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept'
);
res.header('Access-Control-Allow-Credentials', true);
res.header('Access-Control-Allow-Methods', '*'); // enables all the methods to take place
return next();
});
server.set('view engine', 'html');
server.use(cors());
server.use(morgan('dev'));
server.use('/uploads', express.static('uploads'));
server.use(bodyParser.json({ limit: '50mb' }));
server.use(bodyParser.urlencoded({ limit: '50mb', extended: true }));
server.use(cookieParser());
server.use(express.static(path.join(__dirname + 'uploads')));
server.use(compression());
server.use(helmet());
server.use(auth.initialize);
server.use(auth.session);
server.use(auth.setUser);
// console.log('auth.setUser ', auth.setUser);
server.use('/users', require('./users'));
// Redirect all requests to main entrypoint pages/index.js
server.get('/*', async (req, res, next) => {
try {
// #NOTE code duplication from here
// https://github.com/zeit/next.js/blob/cc6fe5fdf92c9c618a739128fbd5192a6d397afa/packages/next-server/server/next-server.ts#L405
const pathName = req.originalUrl;
if (isInternalUrl(req.url)) {
return app.handleRequest(req, res, req.originalUrl);
}
if (isBlockedPage(pathName)) {
return app.render404(req, res, req.originalUrl);
}
// Provide react-router static router with a context object
// https://reacttraining.com/react-router/web/guides/server-rendering
req.locals = {};
req.locals.context = {};
const html = await app.renderToHTML(req, res, '/', {});
// Handle client redirects
const context = req.locals.context;
if (context.url) {
return res.redirect(context.url);
}
// Handle client response statuses
if (context.status) {
return res.status(context.status).send();
}
// Request was ended by the user
if (html === null) {
return;
}
app.sendHTML(req, res, html);
} catch (e) {
next(e);
}
});
// catch 404 and forward to error handler
server.use(function(req, res, next) {
next(createError(404));
});
// error handler
server.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.errorStatus = err.status;
res.locals.errorMessage = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
console.log('err.status ', err.status);
res.status(401).send(err.message);
});
if (process.env.NODE_ENV === 'production') {
server.use(express.static('.next/static'));
server.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, '.next/static', 'index.html'));
});
server.listen(PORT, err => {
if (err) throw err;
console.log(
`> Ready and listening on PORT:${PORT} in the ${process.env.NODE_ENV} environment`
);
});
} else {
server.listen(PORT, err => {
if (err) throw err;
console.log(`> Ready and listening on http://localhost:${PORT}`);
});
}
}
start();
If your files are actually less than 16 mb, please try using this Converter that changes the image of format jpeg / png to a format of saving to mongodb, and you can see this as an easy alternative for gridfs ,
please follow this github repo for more details, please try this method,
https://github.com/saran-surya/Mongo-Image-Converter
I'm using the MERN stack to build an application for the first time.
In order to log HTTP requests I use "morgan".
I managed to send data to mongodb which seems to be working fine. The problem is that my post request is not coming through. It says "pending" for 4 minutes, then fails.
Here's what I think is the relevant part of my code:
"server.js":
const express = require("express");
const mongoose = require("mongoose");
const morgan = require("morgan");
const path = require("path");
const cors = require("cors");
const app = express();
const PORT = process.env.PORT || 8080;
const routes = require("./routes/api");
const MONGODB_URI =
"...";
mongoose.connect(MONGODB_URI || "mongodb://localhost/app", {
useNewUrlParser: true,
useUnifiedTopology: true
});
mongoose.connection.on("connected", () => {
console.log("Mongoose is connected.");
});
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cors());
app.use(morgan("tiny"));
app.use("/api", routes);
app.listen(PORT, console.log(`Server is starting at ${PORT}`));
Then I've put my routes into another file "api.js":
const express = require("express");
const router = express.Router();
const Lane = require("../models/lanes");
router.get("/", (req, res) => {
Lane.find({})
.then(data => {
res.json(data);
console.log("Get request successful!");
})
.catch(error => {
console.log("Error: ", error);
});
});
router.post("/save", (req, res) => {
const data = req.body;
const newLane = new Lane();
newLane.collection.insertMany(data, err => {
if (err) {
console.log(err);
} else {
console.log("Multiple docs inserted");
}
});
});
module.exports = router;
I'm using axios to send the request. This happens after submitting a form within my application.
reducer function:
const reducer = (state, action) => {
switch (action.type) {
case "add":
axios({
url: "http://localhost:8080/api/save",
method: "POST",
data: [...state, { id: uuid(), title: action.title, tasks: [] }]
})
.then(() => {
console.log("Data has been sent to the server");
})
.catch(() => {
console.log("Internal server error");
});
return [...state, { id: uuid(), title: action.title, tasks: [] }];
The reducer is being used by my context provider component, which looks like this:
export function LanesProvider(props) {
const [lanes, dispatch] = useReducer(reducer, defaultLanes);
return (
<LanesContext.Provider value={lanes}>
<DispatchContext.Provider value={dispatch}>
{props.children}
</DispatchContext.Provider>
</LanesContext.Provider>
);
}
The "add" method inside my reducer is being called when submitting a form inside another component.
Please let me know if I can add anything to my question that would help.
Thank you in advance!
you are not sending any response back to client. Try to modify post method like
router.post("/save", (req, res) => {
const data = req.body;
const newLane = new Lane();
newLane.collection.insertMany(data, err => {
if (err) {
console.log(err);
res.send(err)
} else {
console.log("Multiple docs inserted");
res.send("Multiple docs inserted")
}
});
});
I am using JWT to generate a token for access control. I can hit /api/auth/login and get back the token, however, when attempting to hit /api/protected with a GET request, I get 401 Unauthorized.
I've looked through SO and haven't found anything specific although it seems like a routine issue, maybe. I have tried moving the route around in the server.js file to see if that is the issue . I have removed the preceeding slash from the route (from /api/protected to api/protected) and using the latter I get back a bunch of html due to, I think, the app.use(express.static....
I am using Postman to test it but i'm not sure what I'm missing here. I have also made sure to set the authorization to Bearer Token in Postman.
'use strict';
const { Strategy: LocalStrategy } = require('passport-local');
// Assigns the Strategy export to the name JwtStrategy using object destructuring
const { Strategy: JwtStrategy, ExtractJwt } = require('passport-jwt');
const { User } = require('../users/models');
const { JWT_SECRET } = require('../config');
const localStrategy = new LocalStrategy((username, password, callback) => {
let user;
User.findOne({ username })
.then(_user => {
user = _user;
if (!user) {
// Return a rejected promise so we break out of the chain of .thens.
// Any errors like this will be handled in the catch block.
return Promise.reject({
reason: 'LoginError',
message: 'Incorrect username or password'
});
}
return user.validatePassword(password);
})
.then(isValid => {
if (!isValid) {
return Promise.reject({
reason: 'LoginError',
message: 'Incorrect username or password'
});
}
return callback(null, user);
})
.catch(err => {
if (err.reason === 'LoginError') {
return callback(null, false, err);
}
return callback(err, false);
});
});
const jwtStrategy = new JwtStrategy(
{
secretOrKey: JWT_SECRET,
// Look for the JWT as a Bearer auth header
jwtFromRequest: ExtractJwt.fromAuthHeaderWithScheme('Bearer'),
// Only allow HS256 tokens - the same as the ones we issue
algorithms: ['HS256']
},
(payload, done) => {
done(null, payload.user);
}
);
module.exports = { localStrategy, jwtStrategy };
'use strict';
//How does order of code affect how it works?
// YES
require('dotenv').config();
const express = require('express');
const mongoose = require('mongoose');
const morgan = require('morgan');
const passport = require('passport');
const path = require('path');
const { router: usersRouter } = require('./users');
const { router: authRouter, localStrategy, jwtStrategy } = require('./auth');
mongoose.Promise = global.Promise;
// Is this needed if dotenv is in this file also?
const { PORT, DATABASE_URL } = require('./config');
const app = express();
// Logging
app.use(morgan("common"));
// const logRequest = (req, res, next) => {
// const now = new Date();
// console.log(
// `local log - ${now.toLocaleDateString()} ${now.toLocaleTimeString()} ${req.method} ${req.url}`
// );
// next();
// }
app.use(function (req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Content-Type,Authorization');
res.header('Access-Control-Allow-Methods', 'GET,POST,PUT,PATCH,DELETE');
if (req.method === 'OPTIONS') {
return res.send(204);
}
next();
});
passport.use(localStrategy);
passport.use(jwtStrategy);
//app.use(logRequest);
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use('/api/users/', usersRouter);
app.use('/api/auth/', authRouter);
app.use("/api/items", require('./routes/api/items'));
// protected route that needs a valid JWT for access
const jwtAuth = passport.authenticate("jwt", { session: false });
// route to handle static content ie.e *.jpg
app.use(express.static(path.join(__dirname, "client", "build")));
app.get('/api/protected', jwtAuth, (req, res) => {
return res.json({
data: 'Hello World'
});
});
// have react client handle all additional routes
app.get("*", (req, res) => {
res.sendFile(path.join(__dirname, "client", "build", "index.html"));
});
let server;
function runServer(DATABASE_URL, port = PORT) {
return new Promise((resolve, reject) => {
// How is DATABASE_URL used? What is the value? Is it referencing
// DATABASE_URL?
mongoose.connect(DATABASE_URL, { useNewUrlParser: true, useFindAndModify: false }, (err) => {
console.log("Success");
if (err) {
return reject(err);
}
server = app.listen(port, () => {
console.log(`Your app is listening on port ${PORT}`);
resolve();
})
.on('error', (err) => {
mongoose.disconnect();
reject(err);
});
});
});
}
function closeServer() {
return mongoose.disconnect()
.then(() => new Promise((resolve, reject) => {
console.log("Closing server");
server.close((err) => {
if (err) {
return reject(err);
}
resolve();
});
}));
}
if (require.main === module) {
runServer(DATABASE_URL)
.catch(err => console.error(err));
}
module.exports = { app, runServer, closeServer };
enter code hereI am expecting to get back a string that says "Hello World" just to make sure i'm hitting the endpoint correctly. Instead I get the 401 error, GET /api/protected HTTP/1.1" 401enter code here