मेरे पास एक वेबपैक-देव-सर्वर कॉन्फ़िगरेशन है जैसे
const path = require('path')
const CircularJSON = require('circular-json') //just to allow me to log circular references
module.exports = {
...
devServer: {
before(app) {
app.all('/my/route', (req, res) => {
console.log(CircularJSON.stringify(req))//req.query & req.params are empty {}
// I wanna have access to sent payload from Axios here, eg:
const result = {
foo1: req.query.bar1,
foo2: req.query.bar2
}
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(result));
});
}
}
}
समतुल्य अक्ष कॉल की तरह है
axios.post('/my/route', {bar1: 'x', bar2: 'y'}).then(...) => {...})
मैं मार्ग को हिट करने में सक्षम हूं क्योंकि मुझे console.log(CircularJSON.stringify(req))
आउटपुट मिला है, लेकिन req.query
और req.params
खाली हैं। मुझे संदेह है कि यह इस तथ्य के कारण है कि मैं JSON डेटा भेज रहा था, लेकिन अतिरिक्त axios config {headers: { 'Content-Type': 'application/json' }}
के साथ भी मुझे वह डेटा नहीं मिला जो मैं भेजना चाहता हूं।
कोई विचार ?
1 उत्तर
समाधान 'बॉडी-पार्सर' का उपयोग करना था
const path = require('path')
const CircularJSON = require('circular-json') //just to allow me to log circular references
const bodyParser = require('body-parser')
module.exports = {
...
devServer: {
before(app) {
// use bodyParser for axios request
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())
app.all('/my/route', (req, res) => {
console.log(CircularJSON.stringify(req))//req.query & req.params are empty {}
// access them on req.body:
const result = {
foo1: req.body.bar1,
foo2: req.body.bar2
}
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(result));
});
}
}
}
संबंधित सवाल
नए सवाल
json
JSON (जावास्क्रिप्ट ऑब्जेक्ट नोटेशन) मशीन और मानव पठनीय होने के लिए एक क्रमबद्ध डेटा इंटरचेंज प्रारूप है। इस टैग का उपयोग देशी जावास्क्रिप्ट वस्तुओं या जावास्क्रिप्ट ऑब्जेक्ट शाब्दिकों के लिए न करें। इससे पहले कि आप कोई प्रश्न पूछें, एक JSON सत्यापनकर्ता जैसे JSONLint (https://jsonlint.com) का उपयोग करके अपने JSON को मान्य करें।