Notification from the background has been received and parameters have been restored

Sending a post request from "angular->port 4200" to "expressjs server->port 8000".

Referencing this example: https://github.com/kuncevic/angular-httpclient-examples/blob/master/client/src/app/app.component.ts

Encountering two errors:

1) Undefined response from Node.js (data and req.body.text)

2) Message received from background. Values reset.

Angular-Side:

callServer() {
            const culture = this.getLangCookie().split("-")[0];
            const headers = new HttpHeaders()
            headers.set('Authorization', 'my-auth-token')
            headers.set('Content-Type', 'application/json');
            
            this.http.post<string>(`http://127.0.0.1:8000/appculture`, culture, {
              headers: headers
            })
            .subscribe(data => {
            });
        }

ExpressJS Side:

const express = require('express');
const app = express();
const bodyParser = require('body-parser');
var path = require('path');

app.all("/*", function(req, res, next){
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
    next();
});

app.use( bodyParser.json() );       // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({     // to support URL-encoded bodies
  extended: true
}));

app.post('/appculture', function (req, res) {
  var currentCulture = `${req.body.text} from Node.js`;
  req.body.text = `${req.body.text} from Node.js`;
  res.send(req.body)
})


app.listen(8000, () => {
    console.log('server started');
})

Answer №1

It seems like either nothing is being sent or there is no value in body.text

Instead of using req.body.text, try using console.log(req.body).

To confirm if you are actually sending something, consider utilizing console.log(culture) and this.getLangCookie() on the client side. You can also check the network tab in your browser to inspect the request being sent.

Answer №2

Code for Angular:


callServer() {
            const lang = this.getLangCookie().split("-")[0];
            const headers = new HttpHeaders()
            headers.set('Authorization', 'my-auth-token')
            headers.set('Content-Type', 'application/json');
            
            this.http.get(`http://127.0.0.1:8000/language?lang=` + lang, {
              headers
            })
            .subscribe(data => {
            });
        }

Code for Node.js:


app.get('/language', function (req, res) {
  selectedLanguage = req.query.lang;
  res.send(req.body)
})

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

Problem displaying images in Mean stack app using CSS background-image and Webpack

Currently, I am enhancing my skills by working on my own projects. One of the projects I'm focused on right now is designing a MEAN-stack app that utilizes Webpack. In the past, I encountered an issue where I couldn't display images in my app. Ho ...

The method of pausing a function until the result of another function is returned

There is a function named 'updateProfile()' that includes a condition, which checks for the value of variable 'emailChangeConfirm' obtained from another function called 'updateEmailAllProcessing()'. The issue lies in the fact ...

Creating a custom component in Angular 2 that includes several input fields is a valuable skill to have

I have successfully created a custom component in Angular 2 by implementing the CustomValueAccessor interface. This component, such as the Postcode component, consists of just one input field. <postcode label="Post Code" cssClass="form-control" formCon ...

SonarQube Scan reveals absence of code coverage metrics

I have been working on a Jenkins project to perform SonarQube analysis on my NodeJS project. I recently added istanbul as a dependency in my project's package.json. In the Jenkins build configuration, I start by executing a shell script: cd ./project ...

What is the best method for establishing a connection between NodeJS and PostgreSQL?

I'm having trouble figuring out the correct way to connect a PostgreSQL pool in my NodeJS application. I am using Express with Router, and all of my handlers are located in different files. Many people recommend creating a separate file for the DB con ...

What is the process for sending a post request in Ionic 2 to a Node server running on localhost?

When working with Ionic, I utilized a service provider to access HTTP resources. The Service.ts file looks something like this. Here, data is represented as a JSON object. import { Injectable } from '@angular/core'; import { Http, Headers } fro ...

Revise Swagger UI within toggle button switch

My project aims to showcase three distinct OpenApi definitions within a web application, enabling users to explore different API documentation. The concept involves implementing a toggle button group with three buttons at the top and the Swagger UI display ...

What steps do I need to take to set up socket.io on

Currently, I'm delving into the realm of node and socket.io, but encountered a hurdle while attempting to install socket.io. Here's an overview of my actions: I initiated by creating a directory named nodejs A file named app.js was created, alt ...

Retrieve the specific object from the array filter using Mongoose

My mongodb data structure is set up like this {_id:ObjectId(''), "awards" : [ { "award" : "Ballon d'Or", "numberOfTimes" : 6 ...

Is it possible to refresh the component view using the service?

I am interested in developing a NotificationService that will be utilized to showcase a notification from another section. My inquiry is, how can I refresh the view of a component using a service? My ultimate goal is to have the capability to embed a comp ...

The error message "TranslateService not found" seems to be linked to the npm installation process

Encountering an issue with my Angular+Webpack+JHipster+yarn project where a particular error keeps reappearing despite deleting `node_modules` and running 'npm install`. The error seems to be related to the TranslateService provided by a library, not ...

Having issues with the POST method in node.js and express when connecting to a MySQL database

My GET method is functioning perfectly I have a database called stage4 and I am attempting to insert values into it from a frontend page The connection is established, I'm using Postman to test it first, but it keeps returning a "404 error" which is ...

Stopping the subscription to an observable within the component while adjusting parameters dynamically

FILTER SERVICE - implementation for basic data filtering using observables import { Injectable } from '@angular/core'; import { BehaviorSubject, Observable } from 'rxjs'; import { Filter } from '../../models/filter.model'; imp ...

Error unfound: [CLIENT_MISSING_INTENTS]: The Client requires valid intents to function properly

I've gone through multiple tutorials, but I keep encountering an uncaught TypeError. Despite following the suggested solutions, the error persists. I even tried implementing the "intent" solution, but it's prompting a change in "const client = ne ...

A single element containing two duplicates of identical services

I am encountering an issue with my query builder service in a component where I need to use it twice. Despite trying to inject the service twice, it seems that they just reference each other instead of functioning independently, as shown below: @Component( ...

Module not found: The system encountered an error and was unable to locate the file 'os' in the specified directory

I'm currently working on a Laravel/Vue3 project and ran into an issue. When I try to execute "npm run dev", I encounter 37 error messages. I suspect it has something to do with the mix or webpack configuration, but being unfamiliar with this area, I&a ...

Developing a REST API for a component with 18 interconnected elements

Currently, I am developing a REST API to expose a table to an Angular frontend, and I've encountered a unique challenge: The data required for display is spread across 10 different tables besides the main entity (referred to as "Ticket"). Retrieving t ...

The form data does not contain any request body information upon submission

When I try to update using raw JSON, it works perfectly fine. However, when I use form data, the request body appears as an empty object and the update does not happen. Can anyone explain why this is occurring? Below is the snippet of my update code: exp ...

What is the best way to filter out empty arrays when executing a multiple get request in MongoDB containing a mix of strings and numbers?

I am currently working on a solution that involves the following code: export const ProductsByFilter = async (req, res) => { const {a, b, c} = req.query let query = {} if (a) { query.a = a; } if (b) { query.b = b; } if (c) { ...

What is the approach to constructing an observable that triggers numerous observables depending on the preceding outcome?

One of my endpoints returns { ids: [1, 2, 3, 45] }, while the other endpoint provides values for a given id like { id: 3, value: 30, active: true }. I am currently attempting to create an observable that will call the first endpoint and then, for each id r ...