我正在尝试使用 request
模块向我的 API 发送 POST 请求,但我没有得到任何返回,当我通过控制台记录请求数据时,我看到字段未定义,如图所示以下。不知道为什么。
我尝试解决这个问题,但没有成功。我不知道出了什么问题。但是当我尝试通过 POSTMAN 将数据发送到相同的 API 时,它工作正常,如下图所示。所以我不知道为什么当我从应用程序前端发送数据时它不起作用
我需要帮助来解决这个问题。
这是我的服务器端代码
let express = require('express'),
bodyParser = require('body-parser'),
request = require('request'),
//connect = require('connect'),
jobRoutes = require('./routes/jobs'), //ddd
// db = require('./models/app'), //ddd
// helpers = require('./helpers/jobs'),
// fetch = require("node-fetch"),
path = require('path'),
router = express.Router(),
app = express(),
port = process.env.PORT || 3000;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static('public'));
app.use(express.static(path.join(__dirname + '/public')));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use('/api/jobs', jobRoutes);
app.post('/jobs', (req, res)=>{
let formBody = {
title: req.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,
createdAt: Date.now()
};
request.post(console.log(formBody),{url:'http://localhost:3000/api/jobs/', form: formBody
}, function optionalCallback(err, httpResponse, body) {
if (err) {
return console.error('upload failed:', err);
}else{
console.log('Upload successful! Server responded with:', body);
}
return res.redirect('/jobs')
});
})
app.listen(port, process.env.PORT, process.env.IP, ()=> console.log(`Server is running on ${port}`))
这是接收端服务器代码的样子
let db = require ('../models/app');
exports.createJob = (req, res) => {
console.log('The req body:',req.body)
db.Job.create(req.body)
.then((newJob) => {
res.status(201).json(newJob)
})
.catch((err) => {
res.send(err)
})
}
您可以查看当前的repo为了更清楚
最佳答案
But when i try to send data to the same API via POSTMAN it works fine as seen in the image below.
该图像显示来自 Postman 的请求的 Content-Type 将为 application/json
但使用 request
模块的代码将发送一个带有 Content-Type 的请求- application/x-www-form-urlencoded
的类型。
大概(您的“接收端服务器代码”不显示 bodyParser),您的服务器仅支持 JSON 格式的请求。
配置服务器以支持 application/x-www-form-urlencoded
或使请求发送 JSON。
关于javascript - Node 中的请求模块的 POST 请求不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53020075/