I have recently started working with a new stack of technologies and need some help.
I'm working on an existing parse.com app. The guys have been using Sublime 2.
I'm trying to get the app running on WebStorm. After doing some research and trying a couple of things I still can't run it locally.
I have created a new Node.js Express app using WebStorm and that works beautifully, so I'm assuming my environment (WIN10) is set up correctly.
I had to create an package.json for it and change some libraries around like bodyParser (it was using Parse.BodyParser, which is deprecated AFAIK)
I installed all packages/plugins using npm, and WebStorm is no longer complaining about missing references ect..
Here is the first lines:
var express = require('express');
var parseExpressHttpsRedirect = require('parse-express-https-redirect');
var parseExpressCookieSession = require('parse-express-cookie-session');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var app = express();
app.set('views', 'cloud/views');
app.set('view engine', 'ejs');
app.use(parseExpressHttpsRedirect()); // Require user to be on HTTPS.
app.use(bodyParser);
app.use(cookieParser('SecretCodeHere'));
app.use(parseExpressCookieSession({
cookie: {
maxAge: 86400000
}
}));
And then we have this gem at the end of the file:
app.listen();
Now I'm assuming that this works because this gets deployed to parse.com and it does some Magic to host it.
Now the app starts when I run it but I cant connect to it.
I've tried the following:
Connecting to https://localhost:63342/ProjectName/ (this is the default behavior AFAIK) after running gives me 404 Not Found Index file doesn't exist.
Changing the code to :
app.listen(3000, function () {
console.log('App listening on port 3000!');
});
That gives me localhost unexpectedly closed the connection. ERR_CONNECTION_CLOSED
Is there anything else I can try?
If you want to host the server on port 3000, you would need to import the http module
import http = require('http');
http.createServer(app).listen(3000, function () {
console.log('Express server listening on port 3000'));
});
Related
I have been trying for the past hour and a half to debug a project of mine.
The project works fine locally. Routes are systematically not working remotely except for one, the root of the project. I get a Cannot GET message in the browser elsewhere (all other paths).
From what I understand from my readings, this might have something to do with vue-router and might be caused by the server.js file I created in the root folder. The problem might have to do with the fact that my routes are dynamic.
const express = require('express');
const serveStatic = require("serve-static")
const path = require('path');
app = express();
app.use(serveStatic(path.join(__dirname, 'dist')));
const port = process.env.PORT || 3000;
app.listen(port);
This might also be caused by the fact I did not create the project with the history mode (although I'm pretty sure I did). I understand that I might have to go to my webpack config file to solve this, but I don't think I have one.
EDIT: By the way, my VueJS application is just a front-end to the PokéAPI back-end. I didn't build the back-end myself.
Simply creating the project with history mode is not enough. Your browser is trying sending text/html GET requests to the path you navigate to. But your app is a single page application which only has one index.html in /public, so you get 404 errors. Its in the vue-router docs:
To fix the issue, all you need to do is add a simple catch-all fallback route to your server. If the URL doesn't match any static assets, it should serve the same index.html page that your app lives in.
For Node.js+express setup, you can use connect-history-api-fallback package.
npm install --save connect-history-api-fallback
Then change your server.js file to this:
const express = require('express');
var history = require('connect-history-api-fallback');
const serveStatic = require("serve-static")
const path = require('path');
app = express();
app.use(history());
app.use(serveStatic(path.join(__dirname, 'dist')));
const port = process.env.PORT || 3000;
app.listen(port);
In case you don't want to use third-party package you might be able to simply do this:
const express = require('express');
const serveStatic = require("serve-static")
const path = require('path');
app = express();
app.use(serveStatic(path.join(__dirname, 'dist')));
app.get(/.*/, function (req, res) {
res.sendFile(__dirname + "/dist/index.html");
});
const port = process.env.PORT || 3000;
app.listen(port);
But I'd recommend using the package as it handles some edge-cases
I set a public path in vue.config.js like
module.exports = {
publicPath: '/subpath'
};
it works fine when I start the devlopment server with npm run serve (vue-cli-service serve). The app becomes available at localhost:8080/subpath which is exactly what I want. It uses vue-router and at least in development it seems to work perfekt with the /subpath as publicPath.
Problem
I am using Express to serve the app files. Running npm run build the app will be built and stored to ./dist folder (default output folder).
// simplified server.js
app.use(express.static(path.join(__dirname, '/dist')));
app.get('/', (req, res, next) => {
res.sendfile('./dist/index.html');
});
After starting my express server and visiting my browser at localhost:<port>/subpath or localhost:<port> it can't find the necessary files.
// EXAMPLE FROM BROWSER CONSOLE
GET http://localhost:5050/subpath/js/app.6c6daa90.js net::ERR_ABORTED 404 (Not Found)
Which somehow looks obvious to me but I don't know how to set the express server correctly to respect the publicPath setting . Maybe there is a different approach ?
Attempt #1
I made a little change in my express server.js
// app.use(express.static(path.join(__dirname, '/dist')));
/* NEW */
app.use('/subpath', express.static(path.join(__dirname, '/dist')));
This way it should serve the static files from the /dist folder when requested with /subpath/app.js
Result
From Browser console when requesting localhost:<port>/subpath or localhost:<port>
Refused to load the font 'data:application/font-woff2;base64,<omitted>' because it violates the following Content Security Policy directive: "default-src 'none'". Note that 'font-src' was not explicitly set, so 'default-src' is used as a fallback.
Refused to load the image 'http://localhost:5050/favicon.ico' because it violates the following Content Security Policy directive: "default-src 'none'". Note that 'img-src' was not explicitly set, so 'default-src' is used as a fallback.
I played around with express.static and this combination seems to work for me
const path = require('path');
const express = require('express');
const history = require('connect-history-api-fallback');
const app = express();
app.use(history());
app.use(express.static(path.join(__dirname, '/dist')));
app.use('/subpath', express.static(path.join(__dirname, '/dist')));
const listener = app.listen(5050, () => {
console.log(`Open http://localhost:${port} in your browser`);
});
Sidenote : Adding connect-history-api-fallback was not required to solve the initial problem but is required for vue-router to work properly when in history mode.
I am deploying an Apollo Server for my database to heroku and it is giving an application error. It is not simply show that there is a problem with the get route, it says that the application has an error and the error logs say that the app is crashing. It runs fine locally.
I have set up the procfile with: web: node app.js .
I have tried it with the procfile removed.
I have set playground and introspection to true. I saw that that could be the problem but it did not seem to help.
The port is set to process.env.PORT || 8080 .
Here is the minimal code:
const { ApolloServer } = require('apollo-server-express');
const express = require('express');
const db = require('./models');
const typeDefs = require('./data/schema');
const resolvers = require('./data/resolvers');
const app = express();
const server = new ApolloServer({
typeDefs,
resolvers,
context: { db },
introspection: true,
playground: true,
});
server.applyMiddleware({ app });
const PORT = process.env.PORT || 8080;
app.get('/', (req, res) => {
res.send('hello');
});
app.listen(PORT, () => {
console.log(`Server is ready at ${PORT}`);
});
I am also using some other functions (trying to set up a cron process), but those are commented out.
I would expect to get the / get route to at least say hello, or for the /graphql route to display playground. I am getting neither of those options.
It turns out that I needed to add the following to package.json:
"scripts": {
"start": "app.js",
...
}
And I needed to install packages listed in the heroku logs --tail, but I have had those errors before. Writing the script start key into the package.json file is for when you are deploying your server independently of your react (or client) side.
Hi I am a newbie and started to learn about node recently. I took an Heroku tutorial on websockets (https://devcenter.heroku.com/articles/node-websockets) and adapted it for a specific project I was working on. In the example code there was a single index.html file with some embedded javascript. I moved this script out to a separate file and referenced it in the HTML. Everything worked fine locally but doesn't work when i deploy to Heroko. I chatted with the very helpful team at Heroku who informed me that my server side code is serving up all files as HTML and I need to change the code. They gave me some pointers and I tried as many things as I could over several days but to no avail. In the end they recommended coming to this forum as a way to solve the problem as it is beyond their scope. The existing code that serves up the index.html file is as follows:
const express = require('express');
const SocketServer = require('ws').Server;
const path = require('path');
const PORT = process.env.PORT || 3000;
const INDEX = path.join(__dirname, 'index.html');
const server = express()
.use((req, res) => res.sendFile(INDEX) )
.listen(PORT, () => console.log(Listening on ${ PORT }));
At first i edited this to include the line:
app.use(express.static('public'))
but this didn't work. I then amended as follows and it still doesn't work:
const INDEX = path.join(__dirname, 'index.html');
const JS = path.join(__dirname, 'client.js');
const server = express()
.use((req, res) => {
res.sendFile(INDEX);
res.sendFile(JS);
I have looked at other tutorials that work when i run them in isolation but when I try to adapt my above code it simply doesn't work. I would really appreciate if someone out there could point me in the right direction.
BTW this is what Heroku told me:
"To explain a bit further this error Uncaught SyntaxError: Unexpected token < is because the URL for http://thawing-journey-33085.herokuapp.com/client.js isn't serving a javascript file but is instead trying to serve the HTML for the homepage. This suggests you have an issue with the routing in your application which you'll need to review. This is probably because your server.js file doesn't check for any particular URL before sending the index.html file."
Thanks
I serve my static files like this:
// define the folder that will be used for static assets
app.use(Express.static(path.join(__dirname, '../public')));
// handle every other route with index.html, which will contain
// a script tag to your application's JavaScript file(s).
app.get('*', function (request, response){
response.sendFile(path.resolve(__dirname, '../public', 'index.html'));
});
This way i set the static folder in the express.static middleware so i can serve the files. And then i redirect all url request to the index.html
To know more: express static
I've added an expressJS app inside my ember app so I can provide a backend API for my ember app.
My process:
npm install express --save
I created a folder called "server" in the route of my ember application and inside that a file called "server.js".
Yesterday I had it working fine, I already had my ember app running via ember s and tested out the express app using nodemon server/server.js and checking the endpoints I created with Postman.
However this morning when I've tried to run ember s I'm given the following error:
C:\Sandbox\tsodash>ember s
version: 2.3.0-beta.2
Cannot find module 'C:\Sandbox\tsodash\server'
Error: Cannot find module 'C:\Sandbox\tsodash\server'
at Function.Module._resolveFilename (module.js:339:15)
at Function.Module._load (module.js:290:25)
at Module.require (module.js:367:17)
at require (internal/module.js:16:19)
at Project.require (C:\Sandbox\tsodash\node_modules\ember-cli\lib\models\project.js:281:12)
at Class.module.exports.Task.extend.processAppMiddlewares (C:\Sandbox\tsodash\node_modules\ember-cli\lib\tasks\server\express-server.js:115:33)
at Class.<anonymous> (C:\Sandbox\tsodash\node_modules\ember-cli\lib\tasks\server\express-server.js:220:21)
at lib$rsvp$$internal$$tryCatch (C:\Sandbox\tsodash\node_modules\ember-cli\node_modules\rsvp\dist\rsvp.js:1036:16)
at lib$rsvp$$internal$$invokeCallback (C:\Sandbox\tsodash\node_modules\ember-cli\node_modules\rsvp\dist\rsvp.js:1048:17)
at C:\Sandbox\tsodash\node_modules\ember-cli\node_modules\rsvp\dist\rsvp.js:331:11
Naturally I assumed I just needed to use modules.exports = function(){ //..expressjs code}
Full Code
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var request = require('request');
var btoa = require('btoa');
var config = require('./config');
var _ = require('lodash');
module.exports = function(){
var endPoints = config.endPoints;
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
var port = process.env.PORT || 4200;
var router = express.Router();
// middleware to use for all requests
router.use(function (req, res, next) {
// do logging
console.log('Something is happening.');
next(); // make sure we go to the next routes and don't stop here
});
router.get('/', function (req, res) {
res.json({
message: 'TSO Git Dash'
});
});
// ..
app.use('/api', router);
app.listen(port);
console.log('Magic happens on port: ' + port);
}
Still no avail.
Folder structure:
Any ideas? I'm assuming it's something simple that I've missed. But I'm stumped.
As #locks suggested in the comments, there is an express server used in mocks and fixtures. The fix was simple, I renamed the folder and the JS file to "api" and ran ember s and it worked perfectly. It seems to have been a naming conflict.