1

I'm new to web programing and am trying to fetch user data from a .NET Core API using JavaScript but I have been getting a CORS Missing Allow Origin error. I'm aware that this is probably a common and easy issue to resolve but I haven't been able to figure out how to do so. And as mentioned in similar questions I also tried it with the " withCredentials: true" configs for the fetch.

I don't even know at this point whether the issue is server or client side. Could anyone point me in the right direction?

JavaScipt

function ApiController({id}){
    const [user, setUser] = useState({});
    useEffect(() => {
        axios
        .get('https://localhost:7278/User/'  + id, {
                headers: {
                    "Access-Control-Allow-Origin": "*",
                    'Content-Type': 'application/json'
                }
            })
        .then(res => {
                console.log(res);
            })
            .catch( err => {
                console.log(err);
            })
    }, [id]);

UserController.cs

//------------------------------------------------------------------------------
/// <summary>The user controller.</summary>
[Route("[controller]")]
[ApiController]
public class UserController : ControllerBase {

/* 

...

*/

[HttpGet("{userId}")]
public async Task<UserDto> GetUser(Guid userId) {
  return await _userService.GetUser(userId);
}

Startup.cs

/*

...

*/

services.AddCors(options => {
    options.AddDefaultPolicy(builder => {
      builder.AllowAnyOrigin()
        .AllowAnyHeader()
        .AllowAnyMethod();
    });
  });

/*

...

*/

app.UseCors(builder =>
    builder.AllowAnyOrigin()
      .AllowAnyHeader()
      .AllowAnyHeader()
  );

1 Answer 1

3

CORS is configured through server-side, so you need to configure on your Server.

Please make sure you enable CORS on the server side, please refer to Enable Cross-Origin Requests (CORS) in ASP.NET Core for configuration method.

I did a test on this and your problem didn't appear:

JavaScript(refer to this document):

const uri = 'https://localhost:44336/WeatherForecast';
function getItems() {
    fetch(uri, {
        mode: 'cors',
        headers: {
            'Access-Control-Allow-Origin': '*'
        }
    })
        .then(response => response.json())
        .then(data => _displayItems(data))
        .catch(error => console.error('Unable to get items.', error));
}

Then, register CORS on the called server side.(refer to this document).

Result:

enter image description here

If the problem persists, you can try passing Access-Control-Allow-Origin from the server's response:

app.Use((context, next) =>
            {
                context.Response.Headers["Access-Control-Allow-Origin"] = "*";
                return next.Invoke();
            });

Hope this can help you.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.