Cross-Origin Resource Sharing (CORS) and the Access-Control-Allow-Origin problem

I am currently developing an AngularJS web application that communicates with a RESTful Jersey Api as its Backend. I have implemented a function to make API calls, and here is an example:

function Create(user) {
        return $http.post('http://localhost:8080/NobelGrid/api/users/create/', user).then(handleSuccess, handleError('Error creating user'));
    }

Below is the code snippet for the API (POST method):

/**
 * This API creates a new user
 * 
 * @param data
 * @return
 */
@Path("create")
@POST
@Produces("application/json")
public Response create(String data) {

    UserDataConnector connector;
    JSONObject response = new JSONObject(data);

    User userToCreate = new User(response.getString("surname"), response.getString("name"),
            response.getString("mail"), response.getString("username"), response.getString("password"), 0);

    try {

        connector = new UserDataConnector();
        connector.createUser(userToCreate);
    } catch (IOException e) {
        e.printStackTrace();
    }

    return Response.status(Response.Status.OK) // 200
            .entity(userToCreate)
            .header("Access-Control-Allow-Origin", "*")
            .header("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, X-Codingpedia,Authorization")
            .header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT").build();

}

/**
 * CORS compatible OPTIONS response
 * 
 * @return
 */
@Path("/create")
@OPTIONS
public Response createOPT() {

    System.out.println("Called OPTION for create API");
    return Response.status(Response.Status.OK) // 200
            .header("Access-Control-Allow-Origin", "*")
            .header("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, X-Codingpedia,Authorization")
            .header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, OPTIONS").build();
}

I have included an OPTIONS API endpoint for create to ensure CORS compatibility. Despite the functionality working correctly, I am encountering an error on the frontend. The error message reads:

XMLHttpRequest cannot load http://localhost:8080/NobelGrid/api/users/create/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:63342' is therefore not allowed access. The response had HTTP status code 500.

If anyone could provide assistance in resolving this issue, it would be greatly appreciated.

UPDATE:

I came across a similar question on stackoverflow regarding the Access-Control-Allow-Origin header but the suggested solution does not apply to my use case due to the absence of the addHeader(String) method in Response Jersey API.

UPDATE 2

I managed to resolve the initial issue using a solution found at this link: . However, I am now facing another error, which I believe requires a separate discussion.

Thank you in advance for any assistance!

Answer №1

After finding a solution to the initial issue, I came across another error that needs troubleshooting.

https://i.sstatic.net/EhLxk.png

Since this seems to be related to a different argument, I will post a new question for further assistance.

Answer №2

Utilize CORS NPM and integrate it as a middleware.

var express = require('express')
var cors = require('cors')
var app = express()

app.use(cors())

app.get('/products/:id', function (req, res, next) {
  res.json({msg: 'All origins are now CORS-enabled!'})
})

app.listen(80, function () {
  console.log('CORS-enabled web server is now listening on port 80')
})

------------------------- Insert these lines in your app.js file -------------------------

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');

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

Display or conceal div based on chosen options

I am working on a feature that involves three dropdown select boxes, each containing different sets of demographic attributes. My goal is to show a score based on the combination of selections made by the user. For example, if a user chooses Male, 18-24, A ...

Retrieve the cause of the failure using AngularJS $http.post error handling

Here is a snippet of my code: $http.post('http://some.url/', {service: "/", path: "/"}) .then(function (result) { console.log(result); deferred.resolve(result); }) .catch(fun ...

React Error: The property 'i' cannot be read as it is undefined

I am encountering an issue with my code: class Albs extends React.Component{ constructor(props){ super(props); this.state = { i: 0, anh: this.props.hinhanh[this.state.i] }; var hinhanh = ["1.png", "2.png", "3.png"]; this. ...

Ensure that everything within the Container is not see-through

Fiddle:https://jsfiddle.net/jzhang172/b09pbs4v/ I am attempting to create a unique scrolling effect where any content within the bordered container becomes fully opaque (opacity: 1) as the user scrolls. It would be great if there could also be a smooth tr ...

Transformation of callback to promise in JavaScript

I am seeking a way to convert the given callback procedure into a promise. The initial code snippet is as follows: app.get('/api/books', function(req, res) { let booksCallback = function(books) { res.send(books) } DataBase.getBooks( ...

Positioning divs around a circle can be quite challenging

Among my collection of divs with various classes and multiple child divs representing guests at a table, each main div symbolizes a specific restaurant table type. I have created a jsfiddle for demonstration. http://jsfiddle.net/rkqBD/ In the provided ex ...

Creating a KeyListener in Java: A Step-by-step Guide

For my game's highscore screen, I tried implementing a keylistener but it doesn't seem to be working correctly. Below is the section of code that requires fixing. import java.awt.*; import javax.swing.*; import java.awt.event.*; import java.awt ...

Exploring Date Comparisons in AngularJS

Currently, I am in the process of developing a web application using AngularJS and Rails. One of the features involves creating bookings through a bookings function. In the dashboard section of the app, I aim to have two tabs - one for Current Bookings and ...

Exploring the power of data-callbacks in VueJS

For instance, if we have <div data-callback="recaptchaCallback"></div>, the recaptchaCallback function will run as shown: <script> function recaptchaCallback() { alert('OK'); } </script> The code above functions prop ...

"Adjust the placement of a personalized marker on a Google Map using google-map-react

I have incorporated google-map-react into my React project and I have designed custom markers. The markers are displayed at the correct location but from the top left corner: https://i.sstatic.net/e6lGN.png The red dot indicates the exact location. Howe ...

Error: Unable to change image -- TypeError: Cannot assign value to null property 'src'

As I work my way through the textbook for one of my classes, I am practicing by building an image swapping page. The concept is simple - clicking on a thumbnail swaps out the main image and enlarges it as if it were linking to another web page. Despite fol ...

Having trouble getting the form to submit using AJAX

=====ANOTHER UPDATE==== (if anyone is interested!) The previous solution I shared suddenly stopped working for some reason. I added a beforeSend function to my ajax request and inserted the section of my JavaScript code that validates my form into it. It&a ...

Is it possible to bundle Live using Angular 2 and SystemJS-builder, even when attempting to load modules from node_modules?

I'm having a bit of trouble transitioning my angular 2 application into production. It seems to be searching for scripts within the node_modules directory. I'm fairly new to angular 2 and despite spending half a day looking for a solution, I can ...

Reactivate IntelliJ IDEA's notification for running npm install even if you have previously selected "do not show again" option

One of the great features in Intellij IDEA is that it prompts you with a notification when the package.json has been changed, asking if it should run npm install, or whichever package manager you use. I have enjoyed using this feature for many years. Howe ...

What is the best way to test a route using nock and request-promise when the URL includes single quotes?

Trying to test an API call using nock + request-promise is resulting in an error due to mismatched routes caused by single quotes in the API's url. The problem arises from request-promise url encoding the quotes while Nock does not. You can view the ...

Utilize Mongoose to filter data at the database level by providing the options in JSON format

I am currently working on implementing a filter for an array of objects containing product objects. My goal is to filter the data based on the product name in either ascending or descending order. I have written some code for this, but unfortunately, it is ...

swap out a method within a publicly available npm module

Currently, I am using an API wrapper package that utilizes the request module for making API requests. While this setup works well in most cases, I am facing a situation where I need to use this package in a node-webkit environment and replace the request ...

Creating dynamic pie charts with animated effects using JavaScript

Looking to develop an interactive pie chart using JavaScript, I delved into some research and stumbled upon the Google Charts API. However, my primary apprehension lies in the fact that the data is transmitted to Google's server for generating the ch ...

The server appears to be up and running, however there seems to be an issue when attempting to access the API as it is returning an Error: connect ECONNREFUSED 127.0.0.1

Trying to decouple app and server. Successfully running, but encountering Error: connect ECONNREFUSED 127.0.0.1:3000 in Postman when hitting "app.get('/')" API despite making necessary changes. In ./routes/users.js const express = requ ...

Trying to decide between using a Javascript or HTML5 PDF Editor?

I am in need of a solution that enables users to edit PDF files directly on an ASP.NET web page. This functionality is intended for creating templates and adding blocks/form fields to existing PDFs, complete with rulers and other necessary features. Desp ...