res.render for routes on page reload? - express

(Using MEAN with UI Router)
The following code sends a json response for the route defined. This works fine when the template is rendered with UI Router; however, if I reload the page, because the response only contains json, I am left with an empty page rendering no html, only the json response.
router.get('/posts/:post', function(req, res, next) {
req.post.populate('comments', function(err, post) {
if (err) { return next(err); }
res.json(post);
});
});
Assuming this is a standard issue, how can I best allow this page to res.render('index') when the page is reloaded and respond with the json response? Should I,
Create a separate route for the json response which is called as a post promise with UI Router
Have the /posts/:post route simply respond with res.render('index')?
Thank you for any responses, not sure what the usual practise is for such issues!

It took me a while to find a working solution to this due to many of the examples online having different directory structures. I placed a catch all at the end of my routes so that url requests to any UI Router states would not be met with a 404, but instead always return the index.html file.
app.all('/*', function(req, res, next) {
// Just send the index.html for other files to support HTML5Mode
res.sendFile('index.html', { root: __dirname });
});
Then I added prefixes to my express routes, e.g. /api/posts/:post etc. Apparently express routes should not clash with any of the angular defined routes. Thanks to NormySan on reddit for informing me about this.

Related

How to redirect if subdirectory includes hash Nuxt?

At the request of the SEO specialist, I need to implement the following functionality.
I have to redirect if the link contains a capital letter.
For example https//domain.com/#Contacts ==> https//domain.com/#contacts.
In Nuxt I implemented with by creating function on server.js file which located on middleware folder.
But it doesn't work if path contains hash(#)
export default function (req, res, next) {
const url = req.url;
if (url !== url.toLowerCase()) {
res.writeHead(301, { Location: url.toLowerCase() });
res.end()
} else {
next();
}
}
I would be grateful if you answer or help
The part after the hash (fragment identifier) is never going to be sent to the server by your browser, so what you're trying to do is impossible using redirects.
You can access them on the client-side, but I don't think that it would do any good in terms of SEO.

How to pass through multiple requests on a route EXPRESS JS

I'm trying to pass through a view as well as a json file so that I can manipulate it within the view.`
var express = require('express');
var router = express.Router();
var data = require('../monsters.json');
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index');
res.json(data);
});
module.exports = router;
`
It passes through the render of the index.ejs view but in the console there is no indication of a json file with it. Nor is there any way to manipulate the file and read it. I'm not sure if I'm just being silly and the method for passing it through doesn't exist.
EDIT: I've now tried this and am pretty sure its being passed through, is there anyway I can verify that the file has been passed through? `
router.get('/', function(req, res, next) {
res.render('index');
res.header("Content-Type",'application/json');
res.sendFile(path.join(__dirname, 'monsters.json'));
});
`
You can't send multiple responses. You get one response per request.
If the file you want to include is JSON, then you can embed it into a <script> tag in your HTML page using your template engine so everything would be in your HTML page and it can be the one response. Then, the JSON will get parsed automatically into a Javascript object that is available to your page's Javascript.
The other alternative is that you have the Javascript in the page make it's own Ajax call to your server to fetch the desired JSON in a separate http request. You would then make a route on your web server for handling that Ajax request and sending back the desired file.
As far as I am aware, you can't respond twice - you can however seemingly provide a callback to res.render(view, locals, callback) so perhaps you can serve it then. Otherwise, I would bake it into the view by generating the view on the backend with the file content as a parameter.
For more info, see;
http://expressjs.com/en/api.html#res.render

express api responds to GET and POST but not PUT and DELETE through cors but responds properly when the request is local

When I'm sending a request to my express API through Axios, the GET and POST request respond correctly, but PUT and DELETE does not.
This is not a code problem as all my tests are passing, I believe this is related to CORS
I have installed morgan npm package to log the requests to the server.
The GET and POST are working fine, but PUT/DELETE are not and console.log() messages in those route handlers don't even show up!!!
The response from PUT and DELETE is 404
app.js
app.use(cors())
router.js
router.delete('/', (req, res) => {
// this log statement does not show up!
console.log('request recieved')
Controller.DeleteItem(req.body.data.title).then(() => {
res.redirect('/')
}
}
console output
OPTIONS 204
DELETE 404
request
axios.delete('http://localhost:5000/', {
data: {
title: title
}
}
This was discussed outside SO : the issue was that the put and delete routes were placed inside the post route, the indentation (not appearing here) was obvious when seeing the whole code in context.

VueRouter make HTTP request within beforeEach

I am attempting to make an AXIOS request within router.beforeEach. However, it looks like the request is being made with my next destination URL being prepended; if trying to access /client/create, the beforeEach appears to prepend '/client/create' to the request.
Instead of '/api/participant/test/{some_id}' the request is being sent to '/client/create/api/participant/{some_id}'.
I'm not quite sure why this is happening. The documentation indicates that you could use a getPost() method to make requests:
beforeRouteEnter (to, from, next) {
getPost(to.params.id, (err, post) => {
next(vm => vm.setData(err, post))
})
},
However it seems the getPost() method is unrecognized, which could be because of the beforeEach call (the documentation does not show that this could be used with this particular method).
Here is the code with the AXIOS request.
router.beforeEach((to, from, next) => {
console.log(to.params.id);
// Check to see if the cookie exists
if (document.cookie.match(/^(.*;)?\s*participant_token\s*=\s*[^;]+(.*)?$/)) {
axios.get('api/participant/test/' + to.params.id)
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.log(error);
});
}
Any ideas on how this can be avoided? I imagine one could use beforeRouteEnter for each of the routes I have set up, but this would be a more elegant solution.
It should be
axios.get('/api/participant/test/' + to.params.id)
(with forward slash character at the beginner).
The more properly way to set baseURL in axios config
For example:
axios.defaults.baseURL = 'your base url';
First, there is no built-in getPost method in Vue.js. Documentation has mentioned it just as an illustration purpose.
Also, use root relative URL instead of relative URL that you are trying to use.
axios.get('/api/participant/test/' + to.params.id)
You are trying to use relative URL which is causing a problem for you. The more generic way would be to set default base URL in Axios global config.

Express: use separate route file for multiple kinds of http requests on same path

Here are my routes:
app.get('/signUp', routes.signUp);
app.post('/signUp' , routes.signUp);
Here is my separate file for routes.
exports.signUp = function(req, res) {
res.render('signUp');
};
The second block of code is behaviour I want in response to a get request.
How do I respond to a post request? I have already tied up the signUp function with behaviour that responds to get. Do I bundle up the post behaviour in the same function and render the sign up page again? Suppose I simply want to render the view, I don't want the post behaviour to execute in that case so it would be strange to bundle those together.
I believe the express router module should resolve this for you.
route file -
var express = require('express');
var router = express.Router();
router.route("/")
.get(function (req, res) {
res.render('signUp');
})
.post(function (req, res) {
//do something else
})
module.exports = router
index.js/app.js/server.js/whatever you call it.
//..
signUp = require("./routes/signup.js"); //or wherever this is
//...
app.use("/signUp", signUp);
//..