The performance of the Express.js interface is currently lacking

Questions for using Express.js:

Code:

app.use(A)
app.use(B)


{
    const isCurlR = app.use(function (req, res, next) {
        next()
    })
    isCurlR.get('/getLatest', (req, res) => {})
}

{
    const isNotCurlR = app.use(function (req, res, next) {
        next()
    })
    isNotCurlR.get('/getLogs', (req, res) => {})
    isNotCurlR.get('/getCard', (req, res) => {})
}

Router workflow:

A → B → isCurlR → isNotCurlR → /getLatest

A → B → isCurlR → /getLogs

I want: A → B → isNotCurlR → /getLatest

https://i.sstatic.net/ecc0M.png

When trying to access /cli, the isCurlR method works correctly,

However, when visiting /web, it first calls the isCurlR method,

But it should directly use the isNotCurlR method

I prefer not to complicate the interface path. Currently, I achieve this effect using the golang gin library.

Answer №1

Why do you think about implementing the "isNotCurlR" concept in your code?

Here is my suggestion:

app.use((req, res, next) => {
  console.log('A');
  next();
});
app.use((req, res, next) => {
  console.log('B');
  next();
});

{
  const isNotCurlR = app.use(function (req, res, next) {
    console.log('isNotCurlR');
    next();
  });
  isCurlR.get('/getLatest', (req, res) => {
    res.send('ok');
  });
}

Edit

If you can provide more clarification on your issue, it would be helpful. Also, I recommend exploring Express Router as using the Express class may have limitations. You can refer to Router for more information.

Here's an example:

    //Protected
    let admin = express.Router()
    api.use("/admin", admin)
    admin.use((req, res, next) => {
        //Authentication
        try {
            const auth = req.headers.authorization
            if (!auth.includes("Bearer ")) {
                Index.unauthorized(res)
                return
            }
            const token = auth.split(" ")[1]
            req.token = jwt.verify(token, Index.Setting.SecretKey)
            next()
        }
        catch (e) {
            Index.unauthorized(res)
            return
        }
    })

    admin.get("/test", (req, res) => {
        res.json({ role: req.token.role })
    })

The route will be /api/admin/test. Any request that needs to pass through the admin section must undergo proper authentication.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error: Type '() => () => Promise<void>' is not compatible with type 'EffectCallback'

Here is the code that I'm currently working with: useEffect(() => { document.querySelector('body').style['background-color'] = 'rgba(173, 232, 244,0.2)'; window.$crisp.push(['do', 'ch ...

Sending an ID from an array within a *ngFor loop to a different component in Angular: a step-by-step guide

I have a collection of items that I loop through using ngFor. My goal is to pass all its attributes to another component. I attempted to accomplish this with the following code: *ngFor='let item of postList [routerLink]="['/detailed-post&ap ...

I'm having trouble inputting text into my applications using React.js and TypeScript

I am encountering an issue where I am unable to enter text in the input fields even though my code seems correct. Can anyone help me figure out what might be causing this problem? Below is the code snippet that I am referring to: const Login: SFC<LoginP ...

Guide to verifying a value within a JSON object in Ionic 2

Is there a way to check the value of "no_cover" in thumbnail[0] and replace it with asset/sss.jpg in order to display on the listpage? I have attempted to include <img src="{{item.LINKS.thumbnail[0]}}"> in Listpage.html, but it only shows the thumbna ...

TS & Angular: Unlocking the Power of Conditional Interfaces

My user component includes a variable called user, which can be either an Employee or a Student. In my HTML, I have an element {{ user.coure ?? user.department }} I'm encountering an issue in my HTML because some properties in the Employee interface ...

Integrate Angular 2 into the current layout of Express framework

After generating an express structure with express-generator, I ended up with the standard setup: bin bld node_modules public routes views app.js package.json Now, I want to enhance the views and routes directories by organizing them as follows: v ...

It appears that the session data is not maintaining continuity across routes

Currently, I have implemented a middleware to verify whether a user is logged in to access specific pages. This middleware is declared in a separate file from the login route. In this process, the middleware adds the req.originalUrl to the req.session.retu ...

Connecting Node to Heroku with a static IP address without the need for account verification

After deploying my node backend to Heroku, I realized that it makes API calls with a token that is whitelisted to a specific public IP. However, Heroku works with dynamic IPs and only offers static IPs through addons that require a credit card. Does anyo ...

When nodemon is executed, it encounters an "Error: Cannot find module" issue, indicating that it may be searching in the incorrect directory

I recently encountered an issue with my Node.js project that utilizes nodemon. Despite having the package installed (located in /node_modules), I am experiencing an error when trying to start my Express server with nodemon through a script in my package.js ...

Encountering the error message: "TypeError [ERR_INVALID_ARG_TYPE]: The initial parameter should either be a string, Buffer instance, or Uint8Array."

Having trouble with the payment gateway API and subscription creation. Encountering an error that I can't seem to resolve even after debugging. Despite my best efforts, the error persists. The form and everything else seem to be in order, but the err ...

Is there a way to view Deno's transpiled JavaScript code while coding in TypeScript?

As I dive into Typescript with Deno, I am curious about how to view the JavaScript result. Are there any command line options that I may have overlooked in the documentation? P.S. I understand that Deno does not require a compilation step, but ultimately ...

What is the most effective method for data binding using [innerHTML] in Angular 4?

One issue I've encountered is that in Angular 4, there are limited ways to perform data binding between HTML and TypeScript, such as {{myText}}, [], (), and [innerHTML]="myText". Which method is the most effective for binding a simple variable to HTM ...

Achieving functioning routes on a shared hosting environment can be accomplished by following these steps

Hello, I am relatively new to backend development. I am facing difficulties in getting routes from a React app to function properly on my shared hosting space when refreshing /some-page. While I was able to make it work locally with express, I am unsure o ...

Mongoose and Mocha detected an absence of listeners; error in validation

Currently, I am in the process of setting up a unit test for the POST function within my express app. The Mongoose schema that I have in place is quite simple, consisting of two fields, with one being marked as required. During testing with mocha, when I ...

Whenever I attempt to execute yarn build within next.js, an error always seems to occur

When attempting to compile my next.js project using the yarn build command, an error consistently occurs: Error: Export encountered errors on following paths: /settings at D:\web3\futnft\frontend\node_modules\next\ ...

Tips on displaying hyperlinks within a text area in an Angular application

In my Angular application, I am facing an issue with displaying hyperlinks within a text area box for dynamic content. The hyperlinks are not recognized and therefore cannot be clicked. Can someone please advise on how to properly display hyperlinks with ...

Oops! ExcelJs is throwing an error: "Unable to merge cells that are already

Currently, I'm attempting to create an Excel sheet using excelJs. Each order has an array of order items, which could be one or more. My goal is to avoid repeating certain information within the order while iterating through each item in the order. Ho ...

What is the reason behind tsc disregarding the include and exclude options in tsconfig.json?

I am facing an issue with my tsconfig.json file: { "compilerOptions": { "target": "ES6", "lib": [ "DOM", "ES6" ] }, "include": [ "src/server/**/*&q ...

NodeJS Integration with Sinch for Making Calls

I'm currently facing some challenges while trying to implement a basic phone call functionality using the Sinch Calling API. Despite my best efforts, I keep encountering errors in my code. The initial steps involved creating the SinchClient object and ...

Populating a generic array of ObjectId in Mongoose without using a reference

I am currently utilizing mongoose 4.6.6, express 4.13, and passport 0.3. This is the mongoose Schema that I have: var userSchema = new Schema({ nombre: String, apellidos: String, email: String, pass: String, fecha_registro : { type: Date, defau ...