0

I am new to nodeJS server area, need help in understanding how to work with REST API (using express) and deploy the angular application over a singe node server and same ports.

By deploying i want to understand if user hit below url http://localhost:8000/<page_name> then the specified page should open. And is user hit below url using get or post request http://localhost:8000/api/<api_name> then a json or a text will be returned.

How to run both the thing over a single node server.

2 Answers 2

1

Lets assume, you have all your static files in the /public folder of you app. Generally spoken, if you are using express.static, you should also get your index.html because this is handled by default for each directory.

In your case, as you are using Angular, the routing is handled from the client side (SPA). You should only have one single index.html after building your Angular app. All files from your dist folder should then be placed into your /public folder. Then you need to make sure, that initial file serving provides your index.html like so:

In this example static files are served first, then your API and if nothing is found, you are getting back you index file.

const express = require('express');
const app = express();

// serve static files 
app.static(__dirname + '/public'));

// serve your API
app.get('/api/welcome', function (req, res) {
  res.send('Welcome');
});

// fallback routing (server side handling)
app.get(/.*/, function (req, res) {
  res.sendFile(__dirname + ‘/public/index.html‘
});

app.listen(3000);

Next time please make sure, to give all necessary information in your question ;-)

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the suggestion. But if i have two pages , home and admin. Using url http://localhost:3000/home & http://localhost:3000/admin how to open as i am using angular routing but i some how need to return index.html file for the about two request, which i am not able to figure
Adapted answer to your additional question. Hope this will help. What was missing was the default routing to /index.html
Thanks for the brief example explained. Appreciate your help :-) !!
0

With the help from Sebastian, so far I can find a solution but its not working when i am hitting URL for different pages.

const express = require('express');
const app = express();
app.use(express.static('public'))

Please provide your suggestions.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.