ExpressJs and POST from external source to my income router, how to get data - express

I'm getting my hands dirty with Node and expressJS, new with Node and ExpressJS, and there something that I can't get right.
There is a service that POST data (json format {}) to my "income" router, the thing is, a logger helper that check all routers is printing (console.log) the incoming data, but inside the router, I can't get anything (i can't do a console.log for example), not req.body, there is "nothing", just the res.sendStatus(200) that is required for (https://cloud.google.com/pubsub/docs/push).
Any idea about why this happens?
Thanks

There could possibly be some middlewares attached that are actually doing the job, while the router is merely printing the logs. In this case, middleware are attached to be functional well before the code in route gets executed.
Check for app.use or router.post('SOMEPATH',MIDDLEWARE1, MIDDLEWARE2)
ExpressJS's core strength is to modularise the code using middleware.

Related

Vue page cannot open after refreshing the page

I added the routes dynamically to the router and I can visit all pages with router-view. However, when I try to refresh the page I cannot visit the page again although the URL is the same. It is http://localhost:8081/me.
this.$router.addRoute("Main", {
path: '/me',
name: 'Me',
component: () => import(`#/components/Me.vue`)
});
As I said, I can normally visit the page "Me", but when I refresh it, I cannot see its content anymore with the warning:
[Vue Router warn]: No match found for location with path "/me"
I tried to create router with createWebHistory("/") after reading the cause of the error but nothing seems to change. I will appreciate any help.
There are two reasons why this would happen.
First serving SPA application from the server.
Make sure that your back-end is set to serve index.html file for all routes since back-end server is unaware of the routes set by client-side router. Something like express-history-api-fallback-middleware can help is using Node.js/Express.js.
Second problem is that of using addRoute.
As you described, the problem could be that Vue router is taking routing decision before your code in components/common/LeftMenu.vue is getting executed which is responsible for calling addRoute(). Ensure that this code is called before routing decision is being made. Best way would be to move this logic in top-level application component. And, if you can move that to top-level components, that means you can try to declare all routes while defining the router.
Why that should be done?
Using addRoute is not necessarily an anti-pattern but having to rely on addRoute is often code smell. You would really need it in extremely rare scenarios. Routing is a high-level architectural concern for your application and thus better to be declared upfront somewhere at top-level module even before application is getting initialized. Low level components should not attempt to manipulate routing data structure (violation of DIP principles).
One scenario where you might be tempted to use addRoute is taking decision after some data manipulation by the component with addition of some API call. That seems legitimate need but then to address that there are better ways. Considering using route guards (guards support async resolution too!) and prevent user from entering the view till the guard is resolved successfully.

Retrieve a file before anything else happens

Iʼm creating a simple SPA that will retrieve data from an API. The page itself is served by a separate backend process which is the only entity that knows the API address. As such, it also provides an endpoint that, among other things, returns the API URL:
{
"api_url_base": "http://api.example.org/v1"
}
This is needed because the whole thing is deployed at multiple sites where we donʼt have control over DNS records and it may or may not be easy to derive the API URL from the front end appʼs.
Now i need to write my Vue app so nothing can happen until i fetch and process this file. To achieve that, i added to the appʼs beforeMount method:
this.settings = axios.get('/settings.json');
and in my componentsʼ beforeMount:
var comp = this;
app.__vue__.settings.then((response) => {comp.url = response.data.api_url;});
However,it seems the componentʼs beforeMounted often runs before the appʼs, and app. __vue__.settings is undefined when i get to the componentʼs beforeMount.
Where do i go wrong? Am I putting things at wrong places, or is my approach completely wrong?
You can fetch data before mount the vue app.
axios.get('/settings.json').then(response => {
// do something with response
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
}
One way (as suggested in the previous answer) is to make one more call, before anything else. However it brings numerous downsides.
Let me just say that it freezes the loading of your application until the response is received.
There is hope as you can cleverly use (f.e.) good ol' dependency injection to pass the required data to your app.
This article answers this question fully and completely: https://codeburst.io/passing-configuration-to-vue-js-1b96fa8f959

difference between app.use('/users', usersRouter); and require(./routes/users)(app)?

In the express tutorial from mozilla,
https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs/skeleton_website
they write
var usersRouter = require('./routes/users');
app.use('/users', usersRouter);
In other tutorials, they write something like this,
require('./routes/authRoutes')(app);
Are the two pretty much equivalent?
Without seeing the code for the other tutorials that you mentioned I cannot be sure exactly how they consume the app object that is passed to the imported code, but I suspect that whatever code is implemented in the .routes/authRoutes module simply connects a router object to the specified app object. This would most likely be done in the same way as the code that you provided from the Mozilla Express tutorial.
In both cases, a route handler is being defined and then registered as a handler for any routes that match the specified route. In the case that you mentioned that route would be the /users route. So the usersRouter object would have a number of route handlers defined, for example, for routes /abc and /def. So registering the usersRouter object as a route handler for the /users route would mean that the routes /users/abc and /users/def would be handled.

mithril.js not loading new pages properly?

I'm not sure if I'm doing something wrong, or if Mithril is. I have a route, say /admin/channels/edit/1. If I were to navigate to /admin/channels/edit/2 nothing is changed. As each route makes a request to an api no new data is requested from the api. I have the initial request being made in an oninit function. Shouldn't the new url force a new request?
Mithril is re-using the component instance since the routes are technically the same.
There's a useful section in the docs for ways to approach this issue: https://mithril.js.org/route.html#key-parameter
Here is my guess, you could manually call m.redraw() in your network call if you didn't use the default m.request() function.

How do you pass data to react components from express or koa without renderToString?

I'm unable to use React's server side rendering due to my use of client side libraries such as reqwest. I would like to pass some data to my react components, however. Is there a way to do this?
The easiest way to do this is by having api-client.js and api.js. In your browserify/webpack config you set up a client side version. For browserify put this in your package.json (feel free to edit and add webpack).
"browser": {
"./path/to/api.js": "path/to/api-client.js"
}
The second option is better in my opinion, but more difficult to implement. You create an abstract representation of your API that works like this:
var comments = require('./api').get('comments');
comments.getById('7').then(function(comment){ ... });
comments.create({...}).then(...);
On the server api.js simply calls the correct functions, which all return promises. On the client it returns a promise, makes an ajax request to the server, which calls these functions, and sends back the response, and the api client resolves/rejects its promise.
This allows the api to automatically work, and allows you to do additional things like track unfulfilled promises, and pre-populate state on the client, etc. (see react-async for example).