Reputation: 15617
I am POST
ing data to my express
(v.4+) server. However, the response I get back in the browser is in the form:
Response {type: "cors", url: "http://localhost:1111/", status: 200, ok: true, …}
Specifically, the body
of response is a ReadbleStream
, instead of json
or string
I expected as per the response I am sending back.
The server code is:
mongoose.connect('mongodb://localhost/block');
const app = express();
app.set('port', 1111);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use('/', (req, res, next) => { // for cors
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Credentials', true);
next();
});
app.post('/', (req, res) => {
const { dataType, table } = req.body;
const { rows } = table;
const log = {
msgArray: []
};
function saveData(dbModel) {
rows.forEach(row => {
row.data_initiated = new Date();
row.status = 'initiated';
const entry = new dbModel(row);
entry.save(err => {
if (err) {
log.msgArray.push({ err });
}
log.msgArray.push({
msg: 'saved!'
});
});
});
}
if (dataType === 'Contract') {
saveData(Contract);
} else if (dataType === 'Commodity') {
saveData(Commodity);
} else {
saveData(Client);
}
res.send(log).end();
I am using fetch
on the client side to POST
data.
How can I get this to correct send json / string
back to the user?
Thanks,
Upvotes: 0
Views: 640
Reputation: 15617
When using fetch
, the response has to be transformed into JSON
, & returned back. In the subsequent then
, the transformed value is available to be used.
fetch( url, config)
.then( res => res.json())
.then( json => {
console.log( json );
...
}
Its worth mentioning that this is a bit different to how we are used to handling responses when using Axios.js (promise based AJAX library).
P.S: I updated the question to fix the code so that the response is sent correctly.
Upvotes: 2