markkazanski
markkazanski

Reputation: 449

React.js on App Engine as a service querying an API running as another service on same project

The React.js front-end is running as the default service on project-id.appspot.com.

It is querying an API running on API-dot-project-id.appspot.com.

I know proxy settings in package.json only work in development. Using the absolute URL of the API causes CORS issues.

What the best way to resolve this?

Here's what I tried.

I added the following the my backend API service app.yaml:

handlers:
- url: /api/(.*)
  http_headers:
    Access-Control-Allow-Origin: https://project-id.appspot.com

Now I am getting the following error when trying to deploy:

Unknown url handler type.
<URLMap
    secure=default
    static_files=None
    application_readable=None
    auth_fail_action=redirect
    require_matching_file=None
    static_dir=None
    redirect_http_response_code=None
    http_headers={u'Access-Control-Allow-Origin': 'https://project-id.appspot.com'}
    url=/api/(.*)
    script=None
    upload=None
    api_endpoint=None
    expiration=None
    position=None
    login=optional
    mime_type=None
    >

Upvotes: 1

Views: 890

Answers (1)

jgaul
jgaul

Reputation: 601

I think the simplest way to bypass your issue with the same-origin policy is to create (or update) your project's dispatch.yaml file to route API requests to the API service, through the default domain of project-id.appspot.com.

Then you don't have to worry about same-origin issues between your frontend and your API because they're all served from the same domain, even though they're running as separate App Engine services. This approach has spared me a lot of trouble when dividing an application into multiple services.

Your dispatch.yaml file would look something like this:

dispatch:
  - url: "*/api/*"
    service: API

Then your frontend at project-id.appspot.com can simply make requests to https://project-id.appspot.com/api/*, and those requests will be routed to the API service.

Upvotes: 4

Related Questions