What is the best way to divide the dev-server.js file in Vue into multiple separate files?

Currently, I am utilizing vue.js to develop an application and have created a mock login api on localhost in dev-server.js. Now, I am looking to refactor the code related to the login api into a separate file. Do you have any suggestions on how I can achieve this? Additionally, there are some code snippets related to CORS. Here is the existing code:

var app = express()
var bodyParser = require('body-parser')
var multer = require('multer')
var upload = multer()

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}))
// CORS
var allowCrossDomain = function (req, res, next) {
  res.header('Access-Control-Allow-Origin', 'http://localhost:8080')
  res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE')
  res.header('Access-Control-Allow-Headers', 'Content-Type, X-Token')
  res.header('Access-Control-Allow-Credentials', 'true')
  next()
}
app.use(allowCrossDomain)

// Mock localhost api
var apiRoutes = express.Router()
// Login api;
const userAccountList = ['100000', '100001', '100002', '100003']
apiRoutes.post('/user/login', upload.array(), function (req, res) {
  if (userAccountList.indexOf(req.body.account) < 0){
    return res.json({
      code: 50000,
      msg: 'the account or the password is not correct, please try again'
    });
  }
}
app.use('/api', apiRoutes);

Answer №1

(This seems to be a question related to node and express, rather than vue.js)

Express is primarily designed for building web applications using middleware. It may be beneficial to separate your logic into distinct middleware functions.

One approach is to create a separate .js file for your login logic, like so:

// login.js

const userAccountList = ['100000', '100001', '100002', '100003']

const loginMiddleware = function (req, res, next) {
  if (userAccountList.indexOf(req.body.account) < 0){
    res.json({
      code: 50000,
      msg: 'the account or the password is not correct, please try again'
    });
  }
};

module.exports = loginMiddleware;

You can then import it into your app:

// app.js

const loginMiddleware = require('./login');

// ...

apiRoutes.post('/user/login', loginMiddleware);

Refer to the official express documentation for more information on writing middleware: https://expressjs.com/en/guide/using-middleware.html

Answer №2

You might want to consider using a module bundler such as webpack. This tool enables you to organize your code into separate bundles that can be loaded simultaneously.

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

Tips for retrieving the most recent UI updates after the container has been modified without the need to refresh the browser

Currently, I have developed a micro frontend application in Angular using module federation. This application is hosted in production with Docker containers. My main concern revolves around how to update the UI changes for the user without them needing to ...

The form's validation fails to recognize dynamically added input after the initial validation

I am currently working on a form that dynamically adds inputs. Whenever the user selects a different "supplier" from the addMaterialSupplier dropdown, a new input for the price is automatically added. The issue I'm facing is that when I click the bu ...

"Utilizing Vue.js 2 to create an object variable encapsulated within a

When dealing with an array in Vue, you can access objects by looping through the array using v-for and then displaying specific properties within the tags. <div v-for="f in filters"> {f.minValue} </div> <script> { data: { filte ...

Modifying the content of a webpage with the help of Tampermonkey

I'm working on changing a W Text into B using the code below. It's functional, but I'm experiencing two issues. First, there is a lag when refreshing the page where it briefly shows the W text before replacing it with a B. Second, every 20 o ...

What steps can be taken to resolve a 503 error when accessing Heroku?

I am facing some confusion with my deployment process. Initially, I tried using Vercel and everything worked perfectly in the development mode. However, upon deployment, it started throwing errors. So, I decided to try Heroku for deployment but encountered ...

Error: Node-Sass - Unable to download win32-x64-57_binding.node

Currently in the process of getting a retired colleague's program up and running, but when attempting to execute meteor run I encounter this error. While loading package materialize:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" dat ...

Implementing a password toggle feature on a form that extends Django's default Authentication Form

Incorporating a password toggle feature has become quite the challenge as I extend Django's AuthenticationForm to create my UserLoginForm. Attempting to implement this feature has proven difficult, especially since I have been unable to make use of th ...

Using AngularJS to auto-fill input and textarea fields

In order to test local storage, I created a ToDo list using angularJS. Within my mainController, the following code snippet is present: $scope.saved = localStorage.getItem('todos'); $scope.todos = (localStorage.getItem('todos') !== n ...

What is the correct way to execute a jQuery trigger on a checkbox or radio button to simulate a user clicking on it?

My current page utilizes can.js, making it challenging to replicate the issue on jsfiddle.net. The result I am experiencing is as follows: When I click on a checkbox (or even a radio button), an input text box should update accordingly (for example, displ ...

How does the use of nodejs, a server-side scripting language, tie into ReactJs or other front-end languages?

Can Node, being a server-side scripting language, be effectively utilized in the development of front-end applications such as npx create-react-app or npx create-nuxt-app? ...

Tips for sending a localstorage value as a parameter in an axios request

Currently, in my React app, I am using Express to handle all of my database queries. One thing I am attempting to achieve is passing the user id stored in local storage into a post request. This is necessary for my application since it revolves around use ...

Hey there, I'm having some trouble getting the mounted function to work properly in vue.js

My goal is to automatically fetch all products when the specified URL is loaded: '/Admin/ProductsAdmin' Unfortunately, the mounted function is not functioning properly as it fails to load anything upon URL loading. Below is the main.js code snip ...

I am attempting to develop a basic express application, but it doesn't appear to be functioning as expected

I am currently working on developing a straightforward express application. However, I am facing network errors when trying to access it through my browser at localhost:3000 while the application is running in the console. The root cause of this issue elud ...

Encountering the error message "Unable to retrieve /todos."

I recently built a basic Express application and am currently testing the POST route using Postman. However, I keep encountering an error message saying Cannot GET /todos. Any thoughts on what might be causing this issue with the following code? const ex ...

Tips for effectively incorporating customized validation into an array using vuelidate

My array of objects has a specific structure that looks like this varientSections: [ { type: "", values: [ { varientId: 0, individualValue: "" } ] } ] To ensure uniqueness, I implemented a c ...

Convert the canvas to an image by right-clicking

Is it possible to treat the canvas element as an image when using drawImage() to draw on it? When I attempt to right click on the canvas element that has been drawn on, the option "Save image as" does not appear. The right click menu displays: What step ...

Utilizing Gulp for optimizing JavaScript files for web browsers, including import statements

Creating Isomorphic React Components I am looking to transpile my React components server-side into a single bundle.min.js file. However, I am encountering an issue where the import statements are not being resolved in the resulting file. The specific fi ...

Deactivate the form element when a user selects another button

I am facing an issue with two buttons that are linked to the same modal form. Here is the code snippet for the form: <form name="addUser" ng-submit="(addUser.$valid) ? add() : '';"> <div class="form-group has-feedback" ng-class="ad ...

Hiding Properties in NodeJS with MongoDB

My quest is to fetch a user object from my mongodb database : router.get('/', async (req, res) => { var user = await User.findOne({ _id: '5fe30ba2d8f18b353ce6c7c2' }).select('+password +token'); // it's ok, I can r ...

Is there a way to achieve a similar outcome on my site?

Recently, I noticed a mouse-hover effect on two websites and found it quite appealing. https://i.sstatic.net/Ly0gP.png https://i.sstatic.net/oDe1i.png This is the specific effect that caught my attention. Can anyone provide me with insight on how to impl ...