Home > Blockchain >  app.post() is not working plz help tried everything
app.post() is not working plz help tried everything

Time:09-17

the express code is given below:- no matter what i try i get the res.body as ({}) i cannot find the error i even checked the docs but to no avail

const app = express();
const Blog = require('./models/blog');

//to enable post requests

app.use(express.json()); 
app.use(express.urlencoded({extended : true}));


// for views 
// views enable dynamiiic content loading more suitable for real life website
app.set('view engine', 'ejs');

app.listen(3000);


app.get('/', (req, res) => {
    
    // res.sendFile('./html-pages/index.html', {root : __dirname});
    
    //using views and sending objects
    //pasing values to ejs files
    res.redirect('/blogs');
});


//post method
app.post('/blogs', (req, res) => {
    console.log(req.body);
    
    // const blog = new Blog(req.body);
});
app.get('/blogs/create', (req, res) => {
    res.render('create', {title : 'Create a Blog'})
})

the form code :- ejs file this contains the form used to submit a blog=

        <div class="create-blog content">
            <form action="/blogs" method="POST">
                <label for="title">Blog title</label>
                <input type="text" id="title" name:"title" required>
                <label for="snippet">Blog Snippet</label>
                <input type="text" id="snippet" name:"snippet" required>
                <label for="body">Blog Body</label>
                <textarea id="body" required name:"body"></textarea>
                <button>Submit</button>
            </form>
        </div>
    
        

CodePudding user response:

It is quite hard to understand the question, but I see errors in your frontend form. Should look something like this:

<form action="/blogs" method="POST">
  <label for="title">Blog title</label>
  <input type="text" id="title" name="title" required />
  <label for="snippet">Blog Snippet</label>
  <input type="text" id="snippet" name="snippet" required />
  <label for="body">Blog Body</label>
  <input type="text" name="body" required />
  <input type="submit" value="Submit">
</form>

Note that only those fields will be sent in the POST body that has name attribute.

And use bodyparser on backend side.

CodePudding user response:

It looks there is no issue in your javascript file. But in handlebars inside <input> tag you have to use = instead of : that might work fine. like <input name="title" id="title"/>

  • Related