The answer for Node.js - How to send data from html to express solves the problem I have by using a different port for the server. I was wondering how live websites for example this website (stackoverflow's search bar) use a form action that is a directory ("/search") instead of a port similar to the answer at the link? Is node.js incapable of listening to a directory or am I ignorant when it comes to how http requests work?
You listen on a port for http requests. Your front end will do an ajax(asynchronous javascript and xml) request in your javascript code to a route on your server through a port.
If you want a good tool for making easy ajax requests, you can use jQuery, or Axios, and look up how to do ajax with those libraries.
On the back end your server is listening to a port for requests to routes. Set up a route(what you've called a directory) to respond to requests to a particular URL. The example you mentioned showed:
app.post('/myaction', function(req, res) {
res.send('You sent the name "' + req.body.name + '".');
});
Express is a backend framework for doing all kinds of things, but most commonly, handling HTTP requests and rendering HTML. So on the front end when you make your ajax request to /myaction, you can respond like this:
app.post('/myaction', function(req, res) {
res.render('templateFileToRender', { dataToDynamicallyTurnIntoHTML: data } );
});
Express will render your template file, then send the HTML to your front end, and you will update your frontend div or whatever with the rendered HTML.
If you want more info please leave a comment
Related
Simple question which I havn't figured out yet.
Is there a way to get the content type of a request in a feathers hook / context?
I read about potentially using express middleware, but I want to still make use of the service, I dont want to replace it with middleware as from what I understand then I cannot make use of a feathers service afterwards.
Any hints/tips/suggestions are welcome.
Regards,
Emir
As mentioned in the FAQ it is possible to get access to the request object but it should be avoided because transport specific processing should be kept outside of services (for example, when using Feathers via websockets, there won't be a content type at all).
Service call parameters (params) for HTTP calls can be set by using a custom Express middleware so you can add a params.contentType to every service call like this (or use it as a service specific middleware):
app.use(function(req, res, next) {
req.feathers.contentType = req.headers['content-type'];
next();
});
I think I'm having an issue passing a session from my Node backend to my React frontend, but I'm in kind of an I don't know what I don't know situation. Can anyone help?
Here's the issue:
I've got this route on the backend..
app.get('/account', ensureAuthenticated, function(req, res){
res.status(200).json({ user: req.user });
});
which spits out userdata JSON upon a successful Steam Passport authentication. I can verify this works when I check the account page generated by EJS views.
On the React server, I have a root page with a link to Steam auth. It successfully goes to Steam, then redirects back to the root page.
When I try to do a JSON fetch to '/account' from the root React page, the response is no longer JSON, but is HTML from the backend's '/account' template, but I need JSON of course.
I think it's not recognizing me as authenticated, because I get the same HTML response when doing a GET request using Chrome's Advanced REST client extension.
I should also note that I'm proxying the API server via Create React App's proxy feature.
UPDATE: Problem solved.
fetch('https://example.com:1234/users', {
credentials: 'include'
})
It sounds like the issue may be due to the order of app.get calls, or the configuration of your node server – likely the EJS templates.
I would look for where you're doing something like app.set('view engine', 'ejs'); and where you're doing app.get('/account'....
You'll want to do the app.get('/account'.. before you do app.set('view engine...
If you actually hit the /account route you should get either a 401 or the JSON response, not HTML (EJS).
Hi I'm studying about RESTful API and making a website running on local to exercise.
I think RESTful is a quite good way. CRUD operations can be identified by HTTP methods and we can handle them with one url.
But most confusing things to me is that, How can we serve HTML files which are needed to request CRUD operations?
For example, If I'm implementing a forum, I need APIs to CRUD posts in forum like
[GET] /forum - see all posts in forum
[POST] /forum - create a new post
[GET] /forum/:id - see the post of id
[PUT] /forum/:id - modify the post of id
[DELETE] /forum/:id - delete the post of id
Think about how we use a forum, we need at least 3 type of HTML pages.
They are,
1. a page to see all posts in forum.
2. a page to see the specific post.
3. a page to type title and contents to create(or modify) a new post.
First and second type of HTML files can be served easily by GET requests above.
But in case of third type HTML files, I need to use extra parameters with above APIs or make a new API such like /forum/createpost to serve such HTML files.
I think, in the point of view of RESTful, I miss something and need to distinguish serving static (or dynamic) HTMLs and handling CRUD requests.
What is the bestpractices to handle this problem?
I also find some questions about this problem, but I couldn't find a clear answer.
I think you are mixing up two separate parts of the application. One is the REST API that provides the endpoints for CRUD operations. The HTML files that send the API requests are not part of the REST API. They are served by a web application that provides the front-end to the user, and makes calls to the REST API in the backend to fetch the information to display. To put it in another way, the web application making the calls is your Presentation layer. The REST API is your Business logic. Presumably, the REST API interacts with a database to write data to and read data from it. That is your Persistence or Storage layer.
You can use HTTP content type negotiation for that. POST/PUT requests (can) contain a Content-Type header declaring the type of content they're sending, and—more importantly—all requests contain an Accept header declaring the kinds of responses it accepts. If the client is accepting text/html responses, serve an HTML page; if they're accepting, say, application/json responses, serve a "RESTful" JSON response. This way your server can respond to different situations with the appropriate content and the same endpoint can serve as API and as HTML handler.
Alternatively, you can distinguish the request by using an extension: /posts.html serves a plain HTML file, while /posts gets served by a REST endpoint. That can easily be done in the web server configuration.
This might or might not be an anwser to your problem, however since you're working in Node + Express, routing might be a way to go (If I understood your question correctly). Below is an example of server implementation of accepted routes with parameters. Note, you can make parameters optional in some cases if needed.
app.get('/', function (req, res) {
res.send('Index')
})
app.get('/forum', function (req, res) {
res.send('Forum Index')
})
app.get('/forum/:id', function (req, res) {
// To access id you do 'req.params.id'
res.send('Forum Index')
})
app.put('/forum/:id', function (req, res) {
res.send('Modify Forum')
})
app.delete('/forum/:id', function (req, res) {
res.send('Delete Forum')
})
Reference : https://expressjs.com/en/guide/routing.html
I have been trying to do a HTTP POST of some input data from a HTML form to mongodb.
Although I am able to perform the database insertion of my data but unable to redirect to another HTML page after the operation is finished.
I have tried both res.render as well as res.redirect, but nothing seems to work.
However, I am getting a successful post /index 200 followed by a get /home 200.
On the front side maybe write something like this
$.post("/").then(function(data) {
window.location = data.redirectUrl;
});
And in the server side write this
res.send({err: 0, redirectUrl: "/"});
Wondering if there's a clean correct way to load html markup through websockets instead of through a $.ajax({...}) request. I'm somewhat new to websockets so I'm trying to figure out where it can completely replace AJAX and so on...
Right now I just create another 'post' router in my NodeJS app to load the html but I don't know if all of that is even neccessary.
you need websockets mostly if you want to maintain a bidirectional connection between client and server, useful for real-time applications (like chats, stock marketing, e-learning etc.).
if you need to load html mark down, you don't need to go back and forth from client to server many times to load the content and serve it, it will be much elegant and not wasteful way.
you can also use to get route and $.get ajax requests if you do not want to pass additional payload to the server.
Certainly you can pass data through websockets to your client from the Node.js server and, once on the client, just post it to the page.
If you are using socket.io, for example, you can emit an event inside your server with your generated html which will be received at client code:
On the server:
socket.emit('yourFiringEvent', variableContainingYourRawHtml);
On the javascript client:
socket.on('yourFiringEvent', function(htmlResult) {
$("#yourContainerId").html(htmlResult); //jQuery flavour ;-)
});
When your client code receives the event from server will load the data on variableContainingYourRawHtml inside of HtmlResult
If you aren't using it I recommend the use of socket.io library for websocket use, it's quite powerful and easy:
http://socket.io/