简体   繁体   English

使用请求模块发送POST请求,但获取的数据数组几乎为空

[英]Sending a POST request using Request module but getting almost empty array of data

I'm trying to send a POST request to an API using the request module but when i console.log the data sent it seems only the time , approved status and id are sent which is by default from the model schema but the rest data are not sent. 我正在尝试使用请求模块将POST请求发送到API,但是当我console.log发送数据时,似乎仅发送timeapproved状态和id (默认情况下是从模型架构中发送),而其余数据是未发送。 I need help. 我需要帮助。 This is what is sent 这是发送的 在此处输入图片说明 instead of something like this 而不是像这样 在此处输入图片说明

console.log(req.body) when i send data with Postman 我通过邮递员发送数据时的console.log(req.body) 在此处输入图片说明

the request body when i send data with request module 当我使用请求模块发送数据时,请求主体 在此处输入图片说明

 let mongoose = require('mongoose'); //models config let jobSchema = new mongoose.Schema({ title: String, category: String, description: String, type: String, url: String, email: String, apply: String, location: String, company: String, // path: String, approved: {type: Boolean, default: false}, created: {type: Date, default: Date.now, expires: 1000} }) let Job = mongoose.model('Job', jobSchema); module.exports = Job; 

//This is from another file :helpers
exports.createJob = (req, res) => {
    db.Job.create(req.body)
    .then((newJob) => {
        res.status(201).json(newJob)
    })
    .catch((err) => {
        res.send(err)
    })

}

//post
    app.get('/jobs/add', (req, res) => {
        res.render('add')
    })

    app.post('/jobs', (req, res)=>{
        // let formBody = {
     //                 title: req.title,
        //          category: req.category,
        //          description: req.body.description,
        //          type: req.body.type,
        //          url: req.body.url,
        //          email: req.bodyemail,
        //          apply: req.body.apply,
        //          location: req.body.location,
        //          company: req.body.company,
     //                 // path: fullPath,
     //                 createdAt: Date.now()
     //            };
        console.log()
        request.post({url:'http://localhost:3000/api/jobs/', form: {key:'value'}}, function optionalCallback(err, response, body) {
          if (err) {
            return console.error('upload failed:', err);
          }else{
            console.log('Upload successful!  Server responded with:', body);
            }
            return res.redirect('/jobs')
        });
    })
<div class="add-container">
    <form name="myForm"  action="/jobs" method="POST" >
      <div class="form-group">
        <h2>Title(Junior/Graduate/Intern)</h2>
        <input type="text" name="job[title]" placeholder="e.g: Junior Front-End Developer" class="form-control" id="title" required="title">
      </div>

      <div class="form-group">
        <h2>Company Name</h2>
        <input type="text" name="company" placeholder="e.g: Microsoft" class="form-control" required="company">
      </div>
      <div class="form-group">
        <h2>Job Description</h2>

        <textarea id="mytextarea" name="description" placeholder="e.g: We are looking for a Front-End developer with about a year of experience in HTML, CSS, javaScript. Knowledge in React/Vue/Angular is a plus." class="form-control"></textarea>
      </div>

      <div class="form-group">
        <h2>Apply by Website</h2>
        <input type="text" name="url" placeholder="e.g: https://wwww.example.com/jobs" class="form-control">
      </div>
      <div class="form-group">
        <h2>How to Apply</h2>
        <input type="text" name="apply" placeholder="e.g: send your CV or Resume to..." class="form-control" required="apply">
      </div>
      <div class="form-group">
        <h2>Company Location</h2>
        <input type="text" name="location" placeholder="e.g Lagos" class="form-control" required="location">
      </div>
      <div class="form-group">
        <label for="email">Apply by Email</label>
        <input type="email" name="email" class="form-control" id="email" placeholder="e.g: job@gmail.com" required="email">
      </div>
     <!--  <div class="form-group">
        <label>Company logo</label>
        <input type="file" name="file" single class="form-control" id="file" required="file">
      </div> -->

      <button type="submit" class="btn btn-default">Submit</button>
    </form>
</div>

remember to start app.js with body-parser urlencoded and json for json data tested and works 记得使用urlencoded和json来启动app.js,以测试和运行json数据

 //in app.js require("dotenv").config(); //to read env variable not needed const express = require("express"); const bodyParser = require("body-parser"); const mongoose = require("mongoose"); const dbUrl = process.env.DB_URI; //from env variable const Model = require('./models/model.model'); mongoose .connect( dbUrl, { useNewUrlParser: true } ) .then(() => console.log("Connected")) .catch(error => console.log("Failed " + error)); const app = express(); app.use((req, res, next) => { res.setHeader("Access-Control-Allow-Origin", "*"); res.setHeader( "Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept" ); res.setHeader( "Access-Control-Allow-Methods", "GET, POST, PATCH, PUT, DELETE, OPTIONS" ); next(); }); **app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json());** htmlObject = ` <div class="add-container"> <form name="myForm" action="/job" method="POST" > <div class="form-group"> <h2>Title(Junior/Graduate/Intern)</h2> <input type="text" name="job[title]" placeholder="eg: Junior Front-End Developer" class="form-control" id="title" required="title"> </div> <div class="form-group"> <h2>Company Name</h2> <input type="text" name="company" placeholder="eg: Microsoft" class="form-control" required="company"> </div> <div class="form-group"> <h2>Job Description</h2> <textarea id="mytextarea" name="description" placeholder="eg: We are looking for a Front-End developer with about a year of experience in HTML, CSS, javaScript. Knowledge in React/Vue/Angular is a plus." class="form-control"></textarea> </div> <div class="form-group"> <h2>Apply by Website</h2> <input type="text" name="url" placeholder="eg: https://wwww.example.com/jobs" class="form-control"> </div> <div class="form-group"> <h2>How to Apply</h2> <input type="text" name="apply" placeholder="eg: send your CV or Resume to..." class="form-control" required="apply"> </div> <div class="form-group"> <h2>Company Location</h2> <input type="text" name="location" placeholder="eg Lagos" class="form-control" required="location"> </div> <div class="form-group"> <label for="email">Apply by Email</label> <input type="email" name="email" class="form-control" id="email" placeholder="eg: job@gmail.com" required="email"> </div> <!-- <div class="form-group"> <label>Company logo</label> <input type="file" name="file" single class="form-control" id="file" required="file"> </div> --> <button type="submit" class="btn btn-default">Submit</button> </form> </div> `; app.get('/add', (req,res)=>{ res.send(htmlObject); }); app.post('/job', (req,res)=>{ let model = new Model({ title: req.body.title, category: req.body.category, description: req.body.description, type: req.body.type, url: req.body.url, email: req.body.email, apply: req.body.apply, location: req.body.location, company: req.body.company, path: req.body.path, createdAt: Date.now().toString() }); model.save().then(data=>{ res.json({message: 'success', data: data }) }); }) module.exports = app; //in models/model.js const mongoose = require("mongoose"); const dataSchema = mongoose.Schema({ title: { type: Number}, category: { type: Number}, description: {type: String}, type: {type: String}, url: {type: String}, email: {type: String}, apply: {type: String}, location: {type: String}, company: {type: String}, path: {type: String}, createdAt: {type: String} }); module.exports = mongoose.model("data", dataSchema); 

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM