Restangular failing to apply headers during post requests

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?

Answer №1

Here are the steps you can take:

const headers = { headers: { 'Content-Type':'application/json' } };

RestServ.wandem.withHttpConfig(headers).post(pip)

Answer №2

Through my research on the internet, I discovered that Restangular typically sends form data to the server in JSON format by default. Initially, I was misled by the developer tools in Chrome. For those looking to analyze HTTP requests, I highly recommend using Fiddler. If you need to customize the header in Restangular when sending a request from a form, you can implement the following:

//Based on the example provided....
//In case Restangular does not automatically send form data in JSON format

    $scope.getWanPip = function(pip){

        RestServ.wandem.post(pip, {}, {}, {'Content-Type':'application/json'}).then(function(res){
            console.log(res)      
        }, function(err){
            console.log('Error!!!\n', err);
        })

Note the use of two empty curly braces instead of one... I am still unable to successfully execute the post request due to the data being sent within the URL instead of separately. This raises another question...

Answer №3

Avoid sending two null objects, consider sending the following instead:

.post(pip, undefined, undefined, {'Content-Type':'application/json'})

You could also use .customPOST() instead of .post().

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Bringing in a JSON file containing dictionaries of dictionaries with nested dictionaries into Pandas

I am currently extracting a JSON file from the RKI in Germany (equivalent to CDC). The data appears to be structured with dictionaries nested within dictionaries. My main focus is on the data dictionary nested within the "features" dictionary. However, eac ...

Storing TypeScript functions as object properties within Angular 6

I am working on creating a simplified abstraction using Google charts. I have implemented a chartservice that will act as the abstraction layer, providing options and data-source while handling the rest (data retrieved from a REST API). Below is the exist ...

Error in compiled.php on line 7772: Laravel throwing a RuntimeException when sending HTTP requests from Angular

Hey there, I've been encountering an error intermittently while using Angular $http methods with a Laravel API. Can someone please explain what this error means and suggest potential solutions? I've shared the error log on CodePen for easier refe ...

JAX-RS backend powering an Angular frontend

My Java backend uses Jersey, a JAX-RS implementation, running on a Glassfish server on port 8084. I have also created HTML5/JS/AJAX pages to display the data and confirm that the REST implementation is functioning properly. Now, I am working on developing ...

Extracting names from HTML can be done easily by looking for the "@" symbol that the

My HTML structure looks like this: <table id="table-15244" cellspacing="0" class="comment"><tbody> <tr id="comment-37"> <td style="color: #999" class="NV"> </td> <td class="hidden-mob"> ...

Wait for the reaction from react router history to go back

After clicking the submit button in a form, I need to navigate backwards using history.goBack. However, if there is no previous page in the history, I want to redirect to a screen displaying a thank you message using history.replace. const handleSubmit = ( ...

What is the process for creating a progress bar in PixiJS?

Can someone guide me on creating a progress bar similar to the one in PixiJS? Screenshot ...

Designing a menu header against a specific background color resulting in misalignment

I have been working on creating a menu header for my website. If you would like to take a look, here is the link to my jsfiddle page. Unfortunately, I am facing an issue where all my images and text should remain in that grey color scheme but somehow it& ...

Solving repeated function firing with ng-checked in an AngularJS ng-repeat loop

In the HTML code below, there is an ng-repeat that creates checkboxes: <span ng-repeat="name in $ctrl.widgetSelectorNames" class="widget-selectors"> <label class="checkbox" for="{{name}}"> <input type="checkbox" value="{ ...

Utilizing a GLTF asset as the main Scene element in a Three.js project

I'm struggling with incorporating a gltf model as the main scene in Three.js. Specifically, I have a gltf model of an apartment that I want to load from inside and not outside the apartment. I also need the controls to work seamlessly within the apart ...

I'm looking to create an array of tags that contain various intersecting values within objectArray

Initially const array = [ { group: '1', tag: ['sins'] }, { group: '1', tag: ['sun'] }, { group: '2', tag: ['red'] }, { group: '2', tag: ['blue'] }, { grou ...

"Upon choosing a file using the HTML input file multiple element, a triggered event

After selecting multiple files using the input type="file" HTML element, I am eager to start uploading them. Can you tell me which event I should use to execute code immediately after finalizing my file selection? This is what my HTML code looks like: &l ...

Testing NodeJS Database Functionality using Mocha and Asserting with should.js

Currently, I am in the process of testing my NodeJS application using mocha and should. The issue I am facing is that while the first test executes smoothly, the second one fails with an error of null. Interestingly, both tests result in a valid user being ...

What is the reason behind watches not triggering when there are changes in history?

<script setup> import InputChat from '../components/InputChat.vue' import Chat from '../components/Chat.vue' import Layout from "@/components/Layout.vue"; import Sidebar from "@/components/Sidebar.vue"; import ...

Guide on updating property or field names within a personalized JSON serializer

I have created a custom serializer for a specific field. public class SearchSerialize extends StdSerializer<Value> { public SearchSerialize() { super(Value.class); } @Override public void serialize(Value value, JsonGenerator jsonGenerator, Seri ...

Generating XML from JSON data

Looking to convert a JSON file to XML in JAVA for further processing? The JSON structure appears as follows: { "published" : "2014-04-15T12:00:13.760Z", "actor" : { "objectType" : "person", "id" : "a00906a9-d3e3-40b5-8ef2-9e1051828 ...

The SvelteKit server successfully loaded data, displaying it on the sources/index page in the Chrome

I am currently in the process of developing a basic web application that utilizes self-hosted Pocketbase on the backend and SvelteKit as a meta framework. Recently, I discovered that the data loaded by my server is visible in the browser's sources/in ...

I'm having trouble using Discord.js to set up a custom role with specialized permissions for muting users

module.exports = { name: "mute", description: "This command is used to mute members in a server", execute: async function (msg, arg) { const muteRole = await msg.guild.roles.cache.find((r) => r.name == "Mute ...

Deleting validation messages from my MVC controls

I set up some validation in my Model by adding the following code: [Required] [StringLength(60, MinimumLength = 4)] [Display(Name = "Users code")] public string UserCode { get; set; } When c ...

Tips for implementing a conditional statement within an export default clause

I am completely new to web programming and I'm attempting to create a question-answer feature using Vue.js. export default { // Trying to implement an if statement (if character == "Past", then do these steps) "steps": [ { ...