I have been encountering an issue while trying to set the header for a single post request using Restangular. Despite following the documentation here and seeking help from a similar question, the request is being sent as plain text instead of JSON.
My server-side setup includes Express 4.x and communication with MongoDB via Mongoose ORM.
Server side: server.js using Express.js 4.0
'use strict';
var express = require('express'),
morgan = require('morgan'),
port =process.env.PORT || 3000,
bodyParser = require('body-parser'),
methodOverride = require('method-override'),
app = express();
app.use(morgan('dev'));
app.use(bodyParser());
app.use(methodOverride());
app.use(express.static(__dirname+"/app"));
require('./config/models');
require('./config/user_ctrl');
require('./config/comt_ctrl');
require('./config/routes')(app);
app.listen(port);
console.log('Magic happens on port: '+port);
//Server side: routes.js
var pips = require('./user_ctrl');
module.exports = function(app){
app.get('/api/pipplez',pips.getPipplez); //Gets all users in collection
app.post('/api/pipplez/wan',pips.getPipplezById); //Gets the specified user
app.all('/api/*', function(req, res) {
res.send(404);
});
app.get('/*', function(req, res){
res.send('index.html');
});
};
On the client side, my configuration looks like this:
Client side: app.js after config
.factory('userServ',function(Restangular){
var ol = Restangular.withConfig(function(conf){
conf.setBaseUrl('/api/')
});
var an = Restangular.withConfig(function(conf){
conf.setBaseUrl('/api/users/')
});
return{
oldem: ol.one('users').getList(),
wandem: an.one('one')
}
});
Client side: userCtr.js
'use strict';
ting.controller('userCtrl', function($scope, userServ){
$scope.pip = {
name: ''
};
$scope.getOlPips = function(){
userServ.oldem.then(function(rez){
if(rez!=='null'){
$scope.dem = rez;
console.log($scope.dem);
}
}, function(err){
console.log('Error!!!\n', err );
})
};
$scope.getWanPip = function(pip){
//console.log(pip);
RestServ.wandem.post(pip, {}, {'Content-Type':'application/json'}).then(function(res){
console.log(res)
}, function(err){
console.log('Error!!!\n', err);
})
};
$scope.getOlUzas();
});
part of the html
<form>
<input ng-model='pip.unm' maxlength= '20' placeholder='Search for user...'>
<button class="btn btn-primary" ng-click = 'getWanPip(pip)'>Find</button>
</form>
I have thoroughly tested the backend using Postman and confirmed its functionality. While the application can retrieve all records from the database, the POST request results in a 404 error due to the request format being sent as plain text instead of JSON. How can I resolve this issue?