Denied the post request to an API

When attempting to send a post request to my API, I encountered an error indicating that the connection to 'http://127.0.0.1:3000/api/v1/users/login' was refused due to a Content Security Policy directive violation. The specific error message that was caught from the API reads as follows: "Network Error". This issue arises despite using a simple post request through axios.

    import axios from 'axios';
    export const login = async (email, password) => {
      try {
        const res = await axios({
      method: 'POST',
      url: 'http://127.0.0.1:3000/api/v1/users/login',
      data: {
        email,
        password
      }
    }); 
    console.log(res);
  } catch (err) {
    console.log(err);
  }
};

The problem lies in reaching the endpoint of the API. It seems that the middleware being used could be causing this issue. Below is a list of all the middleware currently implemented:

app.use(express.static(path.join(__dirname, 'public'))); //to use static files like css in public          folder
app.use(cookieParser());
app.use(helmet());

app.use(express.json());

app.use(mongoSanitize());

app.use(xss());

app.use(
  hpp({
    whitelist: [
    'duration',
    'ratingquantity',
    'pricediscout',
    'maxGroupSize',
    'difficulty',
    'price',
    'ratingAverage',
   ],
  }),
);

Even after removing some of the middleware, the issue persists and I am still unable to reach the API endpoint.

Answer №1

It appears that the use of Helmet may be contributing to the issue at hand. To resolve this, consider adjusting its configuration to disable content security policy or modifying the meta tag CSP while integrating connect-src rules within the helmet options.

Possible solutions:

  1. Turn off Helmet's content security policy by using helmet.contentSecurityPolicy() and utilize a meta tag for delivering CSP instead.
  2. Delete the meta tag CSP and insert connect-src rules into
    helmet.contentSecurityPolicy(options)
    .

To implement solution #2, you can add the following code snippet:

app.use(helmet({
  contentSecurityPolicy: {
    directives: {
      defaultSrc: ["'self'"],
      connectSrc: ["'self'", 'http://127.0.0.1:3000']
    }
  }
}));

For further information, feel free to consult a similar query here.

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

React-navigation installation in React Native project failed due to ENOENT error - file or directory does not exist

Encountering errors during the installation of react-navigation in my react native project using npm install @react-navigation/native https://i.sstatic.net/uKiPQ.png The installation process reaches halfway, pauses for a few minutes, and then displays an ...

Error encountered while rendering content in an Angular template

I'm currently integrating ngx-carousel into my application. Interestingly, the carousel works perfectly when I manually input the data. However, when trying to fetch the data from the server, it fails to work as expected. Take a look at my code snip ...

The pagination feature in React MUI DataGrid is malfunctioning

I am currently working with a datagrid and implementing server-side pagination. I have set a limit of 5 objects to be returned from the backend, and an offset variable to indicate from which index the next set of data should come. const handlePageChange = ...

Having trouble integrating document.getElementById('password').addEventListener() in a webpack and ES6 environment

I have a project where I am utilizing webpack and ES6 classes. In this particular scenario, I am attempting to trigger the 'onblur' function on input#password but unfortunately, it is not working as expected. Strangely, there are no errors thrown ...

Having trouble rendering to the framebuffer due to issues with the texture

In the process of incorporating shadow maps for shadows, I am attempting to render a scene to a separate framebuffer (texture). Despite my efforts, I have not been able to achieve the desired outcome. After simplifying my codebase, I am left with a set of ...

embedding JSON data into the main template

I'm looking to include a JSON string by injecting some JavaScript on each page. In the master page, I have: public partial class TheMasterPage : System.Web.UI.MasterPage { protected void Page_Init(object sender, EventArgs e) { if (Session[ ...

Having trouble importing the d3-geo package into a Node.js TypeScript project

Seeking a way to test the inclusion of specific latitude and longitude coordinates within different GeoJSON Features using code. When attempting this with: import d3 from 'd3-geo'; // or: import * as d3 from 'd3-geo' // no difference ...

supplying a preset value to a browserify module argument

Currently in the process of revamping a JavaScript codebase and delving into the world of Node.js for the first time. During this journey, I may come across snippets like the following: foo.js var foo = {}; foo.bar = function(baz) { $('body&apos ...

Navigating through objects within arrays within objects in Angular

I seem to be encountering some difficulty in displaying data from an API call on Mapbox. Only one marker is showing up on the map instead of the expected 10 markers. I suspect there might be an issue with my ng-repeat implementation, but I can't pinpo ...

Using Google Chart Tools to manage overlapping labels in visualizations

Currently, I am utilizing Google Chart Tools to showcase a basic line graph, but I am encountering an issue where the labels are overlapping regardless of how I configure the "legend" parameters. The screenshot below illustrates the outcome for legend: { ...

express.js - consolidate multiple routes into a single routing handler in just one line

Is there a way to condense this into one function call? var todo = function (req, res){}; app.get("/", todo); app.get("/blabla", todo); app.get("/blablablabla", todo); Is it possible to simplify it like this: app.get("/", "/blabla", "/blablablabla", to ...

Looping through an array using NgFor within an object

I've been working on pulling data from an API and displaying it on a webpage. Here is the JSON structure: {page: 1, results: Array(20), total_pages: 832, total_results: 16629} page: 1 results: Array(20) 0: adult: false backdrop_path: "/xDMIl84 ...

Sharing Data via JSON for a Pop-Up Display

section of a website, there is a button that, when clicked, triggers a small pop-up. The data being posted appears to be in JSON format as seen in HttpFox. Personally, I have little knowledge of javascript and AJAX. When the specific button is clicked, i ...

"The JavaScript code included in the index.html file is not functioning as expected when called in the main.js file within a

Here is the index.html code for a simple VueJS app that includes a widget from netvibes.com. The widget code is added in the html file and functioning properly. <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLIC " ...

Executing jQuery post request on a div loaded via ajax

I'm facing a challenge with my webpage. I have a section where the content of a div is loaded via ajax. This div contains forms, and after submission, it should update to display the new content without refreshing the entire page. Can anyone guide me ...

The getElementById method in JavaScript can result in a null return value

Why is null returned by the getElementById method in JavaScript? <html> <head> <title>test_elementObject</title> <script language="JavaScript" type="text/javascript"> <!-- var input1 = document.getElementById ( " ...

Successful AJAX Post request functioning exclusively within the Web Console (Preview)

When a user clicks on an element on the website, I have a simple AJAX request to send the ID of that element. However, the script only works in the Web Console under the Network -> Preview section and this issue occurs across all browsers. Here is the ...

Encountering a 404 error with Angular 6 routing after refreshing the page when using an Nginx proxy

I currently have my angular application running within a docker container, exposed on port 83. Additionally, I have a separate spring-boot rest app running inside another docker container, exposed on port 8083. On the host server, there is an Nginx server ...

What sets apart using the loadText function from loadText() in JavaScript?

I've implemented a basic JS function that loads text lines into an unordered list. Javascript function loadText() { document.getElementById("text1").innerHTML = "Line 1"; document.getElementById("text2").innerHTML = "Line 2"; document.ge ...

Tips for resetting the camera position on a canvas

Seeking advice on adjusting the camera position in my code. Any suggestions? I have played around with camera.position.set and added parameters for camera.position.x. function main() { const canvas = document.querySelector('#c'); const rend ...