I have a search box, in which I'm taking the user input using a form.
The form has a certain method and action.
<form action="/public/search" method="GET">
In my routes files, I want to add a controller to this route, I don't know how to access this route in my routes file.
These are all the routes that I tried and didn't work.
Also, I do want it to be a GET request and not a POST request.
const router = require('express').Router();
router.get('/public/search', getSearch);
router.get('/public/search/:id', getSearch);
router.get('/public/search?search=/:id', getSearch);
Related
I am building a simple web app using node js express and cloud firebase functions
i have 2 endpoints,
1. first point renders the form(GET request) and
2. POST endpoint that takes the form data on submit
for some reason firebase skipping the function name in the post url(2nd end point) on form submission but it works fine on local express server
example: if form acion attribute value is "check" and firebase function name is "helloWorld"
the form submit url should be "<default firebase pefix>/helloWorld/check"
but instead the url it posting to is "<default firebase pefix>/check".
firebase function name in the url is getting skipped. which is giving me function not found in location us-central etc
another thing i observed is if i give slash as prefix to action attribute value like "action = "\check". firebase skipping the whole base url and appending from attribute value the port value
i tried a work around by setting the static absolute path (path after production) to the form action attribute.
But i want to if its a bug or am i missing something
<form action="check" method="POST"
<label for="uname"><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="uname" required>
<button type="submit">Login</button>
</form>
// action = "/check" this is skipping total base url all together
const functions = require('firebase-functions');
const express = require('express')
const bodyparser = require('body-parser')
const app = express()
app.set('port',6000)
app.use(bodyparser.json())
app.use(bodyparser.urlencoded({extended:true}))
app.set('view engine', 'ejs');
app.get('/',(req,res)=>{
res.render('formfill')
})
// this below end point is supposed to get triggered on form submission.
// and it is working fine on local express server, but not on firebase functions
app.post('/check',(req,res)=>{
res.send(`you said ${req.body.uname}`)
})
exports.helloWorld = functions.https.onRequest(app);
You can't use Cloud Functions to run a web server or listen on a port. All your code that's trying to run express is not going to work. When you deploy an HTTP function, it's assigned a URL, and you use that URL as the endpoint for requests.
You should review the documentation for HTTP triggers to better understand how this works.
I solved it. i don't know if it is my mistake or lack of knowledge.
so the firebase functions url is something like this
https://us-central1-<project-id>.cloudfunctions.net/<functionname>
in the local firebase server if i go to the functions url(localhost prefix) with or without a slash at the end of the url. my root endpoint is getting consumed. which is fine.
but it is not the case in production url, a slash at end of url(after my function name) is required to load the endpoint. and any anchor tag href in the webpage should omit the prefix slash
example: action = "/check" this is not working but
action ="check/" this is working
so i just removed prefix slash in my action attribute and re deployed, now it is working.
I'm learning about Axios, Mongoose and Express and have come across the following issue. I am working on one schema that needs to have 2 different get requests accessible for when i need them. problem is that when i call the route with attending it still executes the route with info. How can i target the attending route on the backend correctly?
FRONT END
//finds a users info using findOne
axios.get("/api/user/" + info); //info is a variable
//finds a users info
axios.get("/api/user" + attending); //attending is a variable
ROUTES FILE ON BACKEND
router
.route("/:info")
.get(UserController.findOne);
router
.route("/:attending")
.get(UserController.findOneAndUpdate);
I have also tried changing the routes like below but still it hits the info route and not the attending route .
FRONT END
axios.get("/api/wmUser/getAttending" + eventCode);
ROUTE ON BACKEND
router
.route("/:info")
.get(UserController.findOne);
router
.route("/getAttending/:attending")
.get(UserController.findOneAndUpdate);
You are sending an axios GET request which will target
router
.route("/:info")
.get(UserController.findOne);
If you want to hit the PUT route on the backend, you need to do a axios.put request on the frontend.
Both your axios get requests from the frontend will hit the get on the backend with different params (namely info and attending).
I have an express server. I have two routes as get methods.
app.get('/main',(req, res) => {
res.sendFile(`main.html`, {root: staticPath});
});
app.get('/signin', (req, res) => {
res.sendFile('signin.html', {root: staticPath});
});
I want to build my app as a single page react application. But before I let the user see this single page, I want to show a sign in, sign up screen. So when user clicks the sign in or sign up buttons, I want to send signin.html as response from the express server.
Here is my code on the browser from a react class
SignIn(){
axios.get('signin');
}
I can console.log() from the express route and verify that the code gets executed within the 'signin' route, but the html view doesn't change on the browser even though I send back a html file. How do I make it happen?
I'm by no means an expert, but here are my two cents. Instead of setting up your front end to receive an HTML file from the server, a more efficient approach would be the following.
Build the signup and login pages on the front end.
Set up routing between these pages.
Send the login/signup details from client to server via /login or /signup routes that you set up in Express. These details would usually be in the req.body object (make sure to install the bodyparser package from NPM).
You could then use JWTs to authenticate users and maintain sessions.
If you're looking for server-side rendering with React, here is an article for your reading pleasure :) Sorry if I made no sense.
I'm making a basic web app with Node.js and Express 4 and I'm trying to implement a "follow" function. I did some inspecting on the Github website and noticed it used a form with a follow button that would post to the server to follow a user. I think this sounds like a good approach but when I post I don't want to have to reload the page just like the github website.
How does one this inside of Express 4? Everything I put inside the .post route always end up in a page load. I'm pretty sure in jQuery's ajax method you can just return false and nothing will happen to the page, just the request will be sent which is what I want to happen because I'm using a RESTful api and I want to add the user to the current user's following but I don't want to have to use jQuery just for this function. I would prefer it be done in Express if possible, though any help would be appreciated.
views/user.handlebars
<h1>{{user.displayName}}</h1>
<p>#{{user.username}}</p>
<form action="" data-userid="{{user._id}}" method="post">
<button name="follow" type="submit">Follow</button>
</form>
routes/users.js
app.route('/:username')
.get(function(req, res) {
// get :username user from api and load info
...
})
.post(function(req, res) {
// don't reload page
???
// send PUT :username user to current users following array
...
});
So you're on the right track, but instead of putting your actions in the HTML (in your jade file) you're gonna have to add a script section to your jade and use javascript to attach an onClick event to the button so that when you press the button you invoke your ajax method.
Let me know if that doesn't make sense.
I am pretty new to node and express.js and I'm new to the concept of REST applications as well. I want to code a typical CRUD app, some sort of diary. Hence, I have a collection of entries, can view a single entry and can add, edit and delete an entry.
I'm not quite getting yet, how URi's have to be set up to represent a REST conform API. I would create something like this in my app.js:
// GET REQUEST ROUTING
app.get('/', diary_router.home);
app.get('/entries/', diary_router.listEntries);
app.get('/entries/:id', diary_router.getSingleEntry);
// POST REQUEST ROUTING
app.post('/entries/', diary_router.addEntry);
// PUT REQUEST ROUTING
app.put('/entries/', diary_router.updateEntry);
// DELETE REQUEST ROUTING
app.delete('/entries/', diary_router.deleteEntry);
Could that be called a REST conform interface? Should I rather add the respective action in the routes, such as this and does the item-ID need to be shown in the URL for PUT and DELETE actions, too?:
// GET REQUEST ROUTING
app.get('/', diary_router.home);
app.get('/entries/', diary_router.listEntries);
app.get('/entries/show/:id', diary_router.getSingleEntry);
// POST REQUEST ROUTING
app.post('/entries/add/', diary_router.addEntry);
// PUT REQUEST ROUTING
app.put('/entries/update/:id', diary_router.updateEntry);
// DELETE REQUEST ROUTING
app.delete('/entries/delete/:id', diary_router.deleteEntry);
What would be best practice here? Any help is much appreciated.
B.
In the loose definition of REST that we seem to have converged on in web-land, the first option seems to fit best.
Edit: and yes, you should specify the ID in the PUT and DELETE routes.
HTTP is a really cool protocol for applying verbs (request methods) to nouns (URLs). In that spirit, it's probably best to use the request method to differentiate what you want to do to the resource that you're requesting.
Note: you can use the methodOverride middleware in express if you're worried about browsers not being able to use arbitrary HTTP methods.
The way the methodOverride middleware works is that you use an <input type="hidden" name="_method" value="PUT"> or similar to specify the method, despite it just being a regular POST request, and the methodOverride middleware will set the method property on the request that you get in your express application. This way, you can signal the intended request method without the client actually having to support that method.