Home > front end >  Call an imported Function in app.get(/) in nodeJS
Call an imported Function in app.get(/) in nodeJS

Time:12-11

Can I call an imported function in app.get("/")? is it good practice?

Does this also mean that all logic must be done in the addArticle function?

post.js

const addArticle = async post => {
 const postData = {
  body: post.body,
  title: post.title,
  username: post.username
 };
 const { data } = await axios.post(
  `${BASE_URL}/data/`,
  postData
 );
 return data;
}
catch (err) {
        console.log(err)
    }

index.js

const express = require('express')
const axios = require('axios')
const postfunc = require (./post.js)
const app = express()

app.get("/", post.addArticle)

app.listen(3001)

CodePudding user response:

It’s acceptable to pass your route handler however you see fit. However, your addArticle function doesn’t conform to express route handler signature.

Your function should handle two arguments, being express.Request and express.Response instances respectively.

Finally, note that returning a value from a route handler does nothing — if you want to send that value to the client, you’ll need to use res.send or similar method.

  • Related