Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bug: still request data from browser even after using getBackendSrv and adding routes settings in plugin.json #1661

Closed
1 of 5 tasks
liubq919 opened this issue Mar 28, 2025 · 7 comments · Fixed by #1671
Closed
1 of 5 tasks
Assignees
Labels
documentation Changes only affect the documentation type/docs Changes only affect the documentation type-docs

Comments

@liubq919
Copy link

Which package(s) does this bug affect?

  • Create Plugin
  • Sign Plugin
  • Plugin E2E
  • Plugin Meta Extractor
  • Plugin ESLint Rules

Package versions

"@grafana/data": "^11.5.2",
"@grafana/runtime": "^11.5.2",
"@grafana/ui": "^11.5.2",
"@grafana/schema": "^11.5.2",

What happened?

Follow the How to use the data proxy in data source plugins with a custom configuration page.
but it does not work, the request still happens from the browser, not the backend.

What you expected to happen

request data from grafana backend not browser

How to reproduce it (as minimally and precisely as possible)

  1. In this environment...
  2. With this config...
  3. Run '...'
  4. See error...

Environment

"@grafana/data": "^11.5.2",
    "@grafana/runtime": "^11.5.2",
    "@grafana/ui": "^11.5.2",
    "@grafana/schema": "^11.5.2",

Additional context

grafana: v11.2

@liubq919
Copy link
Author

  • plugin.json
  "routes": [
    {
      "path": "myRoutePath",
      "url": "{{ .JsonData.apiUrl }}"
    }
  ]
  • datasource.ts
  constructor(instanceSettings: DataSourceInstanceSettings<MyDataSourceOptions>) {
    super(instanceSettings);
    this.baseUrl = instanceSettings.jsonData.apiUrl!;
    console.log(this.baseUrl);
  }
  • ConfigEditor.tsx
export function ConfigEditor(props: Props) {
  const { onOptionsChange, options } = props;
  const { jsonData } = options;

  const onApiUrlChange = (event: ChangeEvent<HTMLInputElement>) => {
    onOptionsChange({
      ...options,
      jsonData: {
        ...jsonData,
        // notice we set the apiUrl value inside jsonData
        apiUrl: event.target.value,
      },
    });
  };

  return (
      <InlineField label="apiUrl" labelWidth={12}>
        <Input
            onChange={onApiUrlChange}
            value={jsonData.apiUrl || ''}
            placeholder="json field returned to frontend"
            width={40}
        />
      </InlineField>
    );
}

@hugohaggmark hugohaggmark self-assigned this Apr 2, 2025
@hugohaggmark
Copy link
Contributor

Hi @liubq919 and thanks for taking the time to report this issue 🙌

In your datasource.ts file can you try to change from url: ${this.baseUrl}/todos to url: ${this.baseUrl}/myRoutePath/todos and see if that works for you?

async query(options: DataQueryRequest): Promise<DataQueryResponse> {
    const response = getBackendSrv().fetch<TODO[]>({
      // You can see above that `this.baseUrl` is set in the constructor
      // in this example we assume the configured url is
      // https://jsonplaceholder.typicode.com
      /// if you inspect `this.baseUrl` you'll see the Grafana data proxy url
      url: `${this.baseUrl}/myRoutePath/todos`, // <==== need to use the route defined in plugin.json here
    });
    // backendSrv fetch returns an observable object
    // we should unwrap with rxjs
    const responseData = await lastValueFrom(response);
    const todos = responseData.data;

    // we'll return the same todos for all queries in this example
    // in a real data source each target should fetch the data
    // as necessary.
    const data: PartialDataFrame[] = options.targets.map((target) => {
      return {
        refId: target.refId,
        fields: [
          { name: 'Id', type: FieldType.number, values: todos.map((todo) => todo.id) },
          { name: 'Title', type: FieldType.string, values: todos.map((todo) => todo.title) },
        ],
      };
    });

    return { data };
  }

@hugohaggmark hugohaggmark added type/docs Changes only affect the documentation documentation Changes only affect the documentation type-docs labels Apr 2, 2025
@hugohaggmark hugohaggmark moved this from 📬 Triage to 🔬 In review in Plugins Platform / Grafana Community Apr 2, 2025
@liubq919
Copy link
Author

liubq919 commented Apr 2, 2025

Hi @liubq919 and thanks for taking the time to report this issue 🙌

In your datasource.ts file can you try to change from url: ${this.baseUrl}/todos to url: ${this.baseUrl}/myRoutePath/todos and see if that works for you?

async query(options: DataQueryRequest): Promise {
const response = getBackendSrv().fetch<TODO[]>({
// You can see above that this.baseUrl is set in the constructor
// in this example we assume the configured url is
// https://jsonplaceholder.typicode.com
/// if you inspect this.baseUrl you'll see the Grafana data proxy url
url: ${this.baseUrl}/myRoutePath/todos, // <==== need to use the route defined in plugin.json here
});
// backendSrv fetch returns an observable object
// we should unwrap with rxjs
const responseData = await lastValueFrom(response);
const todos = responseData.data;

// we'll return the same todos for all queries in this example
// in a real data source each target should fetch the data
// as necessary.
const data: PartialDataFrame[] = options.targets.map((target) => {
  return {
    refId: target.refId,
    fields: [
      { name: 'Id', type: FieldType.number, values: todos.map((todo) => todo.id) },
      { name: 'Title', type: FieldType.string, values: todos.map((todo) => todo.title) },
    ],
  };
});

return { data };

}

@ hugohaggmark, thanks hugohaggmark, retried but it still does not work, myRoutePath is part of the url that i need to request, still not proxy request.

the request i need to request:

http://127.0.0.1:8848/all-spans/d3e10152e97f3de52df81e25d93122e0

after adding myRoutePath, it becames

http://127.0.0.1:8848/myRoutePath/all-spans/d3e10152e97f3de52df81e25d93122e0

@hugohaggmark
Copy link
Contributor

Thank for the update @liubq919

Are you able to share your code and your grafana.ini file?
I just created a new plugin using the supplied documentation and it just works. Are you sure you restarted the grafana server after changing the plugin.json?

@hugohaggmark
Copy link
Contributor

hugohaggmark commented Apr 2, 2025

If I use the Query Inspector on my dashboard it looks like this

Image

network tab in the browser

Image

@liubq919
Copy link
Author

liubq919 commented Apr 4, 2025

@hugohaggmark thanks hugohaggmark, rebuild my data source plugin and restart grafana server, it works now, thanks for your help.

@liubq919 liubq919 closed this as completed Apr 4, 2025
@github-project-automation github-project-automation bot moved this from 🔬 In review to 🚀 Shipped in Plugins Platform / Grafana Community Apr 4, 2025
@hugohaggmark
Copy link
Contributor

Great to hear that @liubq919 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
documentation Changes only affect the documentation type/docs Changes only affect the documentation type-docs
Projects
Status: 🚀 Shipped
Development

Successfully merging a pull request may close this issue.

2 participants