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

时间:2018-10-16 21:31:24

标签: javascript node.js post request

我正在尝试使用请求模块将POST请求发送到API,但是当我console.log发送数据时,似乎只有timeapproved状态和id默认情况下从模型模式发送,但不发送其余数据。我需要帮助。 这是发送的 enter image description here 而不是像这样 enter image description here

当我用邮递员发送数据时,

console.log(req.body) enter image description here

使用请求模块发送数据时的请求正文 enter image description here

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>

1 个答案:

答案 0 :(得分:0)

请记住使用urlencoded的正文解析器和json来启动json数据的app.js 经过测试和工作

//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="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>
  `;


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);

enter image description here