I was making my own api in javascript using node and express for flutter, but when I try to send the required body to my api I am getting error that there is no data that is required. this is my api code: index.js(main file):
const express = require('express');
const authRouter = require('./routes/auth');
const PORT = 3000;
const app = express();
app.use(express.json());
app.use(authRouter);
app.get('/', (req, res) => {
res.send("hello world");
})
app.listen(PORT, '0.0.0.0', () => {
console.log(`connected at port ${PORT}`)
});
routes/auth file:
const express = require("express");
const authRouter = express.Router();
authRouter.post("/fetchedData", async (req, res)=>{
try {
const {sampleName,samplepara} = req.body;
res.status(200).json({sampleName,samplepara});
console.log("data received");
console.log(sampleName + " " + samplepara)
// res.send(sampleName, samplepara)
}
catch (e) {
res.status(500).json({ error: e.message })
console.log(e)
}
});
// signin Route
module.exports = authRouter;
sending data from flutter code:
var samples = {
'sampleName' : 'Ammar',
'samplepara' : 'this is the para'
};
var jf = jsonEncode(samples);
var url = Uri.parse('http://myIPaddress:3000/fetchedData');
var response = await http.post(url,
body: jf,);
print('Response status: ${response.statusCode}');
print('Response body: ${response.body}');
but when I try to make a request from vs code extension thunder client so it is working
Add Content-Type header to define data as json. Something like this:
http.post(
Uri.parse('https://jsonplaceholder.typicode.com/albums'),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode(<String, String>{
'title': title,
}),