-
-
Notifications
You must be signed in to change notification settings - Fork 7k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Is it possible to 'get' data using POST with json-server? #453
Comments
It would be helpful if they answered this issue... i'am facing the same problem |
Out of the box it's not possible, sorry. With REST, making a POST usually mean that you request a change and if you want to query GET is the right verb. That said, using the project as a module, you can fake it: // server.js
var jsonServer = require('json-server')
var server = jsonServer.create()
var router = jsonServer.router('db.json')
var middlewares = jsonServer.defaults()
server.use(middlewares)
server.use(jsonServer.bodyParser)
server.use(function (req, res, next) {
if (req.method === 'POST') {
// Converts POST to GET and move payload to query params
// This way it will make JSON Server that it's GET request
req.method = 'GET'
req.query = req.body
}
// Continue to JSON Server router
next()
})
// If you need to scope this behaviour to a particular route, use this
server.post('/comments', function (req, res, next) {
req.method = 'GET'
req.query = req.body
next()
})
server.use(router)
server.listen(3000, function () {
console.log('JSON Server is running')
}) I would suggest checking https://expressjs.com/ docs and https://github.com/typicode/json-server#module And if you need to customize more, you can also access router's lowdb instance using Hope this helps :) |
@typicode i tried pasted above code ,but i found that i failed to get data |
Closing as this question is answered. |
This is what worked for me: Instead of writing the // middleware-1.js
module.exports = function (req, res, next) {
if (req.method === 'POST') {
// Converts POST to GET and move payload to query params
// This way it will make JSON Server that it's GET request
req.method = 'GET'
req.query = req.body
}
// Continue to JSON Server router
next()
} Next, this is in my {
//...
"middlewares": ["middleware-1.js"],
//..
} The
Good Luck. |
@appsparkler thanks a lot for your answer, it helped me fixing a problem in the project i'm working at the moment. Moreover, while writing the middleware and testing your solution, I discovered a weird behaviour when the query result cointained a field with the same name of a field contained in the POST original body. I'll explain it better, using an example from the code I wrote HTTP request(variable's names are voluntarily changed)
MIDDLEWARE
RESULT: example:
In this case, the result will be an empty res object. I hope this will be useful and spare some hours to someone :) |
hi @mircolac i'm not sure if this would work but another thing that we can include in the // ...
req.query = req.body;
delete req.body; //or null (if that works)
// ... this might avoid the |
Hey @appsparkler Thanks anyway :) |
@typicode Is there another way which not to make the method to 'get' ? Thanks. |
@leohxj Is there an issue with setting your method to get, like so?
As you can still POST to your server, .then use the response. |
I needed to reroute the URL but resetting const jsonServer = require('json-server');
const server = jsonServer.create();
const router = jsonServer.router('db.json');
const request = require('request');
const middlewares = jsonServer.defaults();
server.use(middlewares);
server.use(jsonServer.bodyParser);
server.post('/login',(req,res,next) => {
// We don't care if we don't check the password we just want to receive a user back for testing
let url = 'http://localhost:3000/user?login.username=' + req.body.username;
request({url: url, json: true},(err, response, body) => {
res.send(body);
});
}); // post(/login)
server.use(router);
server.listen(3000, ()=>{
console.log('http://localhost:3000 Running...');
}); |
It seems like the only way is write a middleware that changes requests from POST to GET:
You can still have and react to POST requests if you do this BEFORE the middleware:
|
I've been facing the same issue. My team demands sending their query data in the body, so they're using a POST instead of a GET for querying data. After searching the web I created a So, for anyone who's searching for a compound // json-server.js
const jsonServer = require('json-server');
const bodyParser = require("body-parser");
const server = jsonServer.create();
const router = jsonServer.router('./db.json');
const middlewares = jsonServer.defaults();
server.use(bodyParser.json());
server.use(bodyParser.urlencoded({
extended: true
}));
server.use(function (req, res, next) {
if (req.method === 'POST') {
// Converts POST to GET and move payload to query params
req.method = 'GET';
req.query = {}
for (let p in req.body) req.query[p] = req.body[p];
}
// Continue to JSON Server router
next();
});
server.use(middlewares)
server.use(router)
const port = 3000;
server.listen(port, () => console.log(`JSON Server is running on port ${port} ...`)) |
Thanks for the details @SetTrend. |
I set up a middleware like this and works fine for me: middleware1.js module.exports = function (req, res, next) {
if (req.method === 'POST' && req.originalUrl === '/user/login') {
return res.jsonp({ token: "foo" })
}
next()
} And run
|
Thanks for this!! |
maybe, it is much easier and you don't have to change methods: const server = jsonServer.create();
const router = jsonServer.router(db);
const middlewares = jsonServer.defaults();
const port = 3000;
// @ts-ignore
router.render = (req, res) => {
if (req.originalUrl === '/whatever' && req.originalMethod === 'POST') {
res.jsonp({
result: {
agent: 'James Bond',
code: '007',
},
});
} else {
res.jsonp({
result: res.locals.data,
});
}
};
server.use(middlewares);
server.use(router);
server.listen(port, () => {
console.log(`JSON Server is running on port ${port}`);
}); |
Note This prevents that:
|
@appsparkler in this case, if i add Is there no other way to do this work within only "json files" without needing a |
Hi @Jackie098, this was a long time ago (5-6 yrs). I've not been using Thanks & Regards |
@appsparkler i understand! Thanks for answered me 😁❤️ |
Hi,
I am trying to get response using POST. My POST body has some key-value pairs which determine what needs to be responded.
Is it possible to get data back from POST method ?
Thanks
The text was updated successfully, but these errors were encountered: