0

I want to consume this api http://www.mindicador.cl/api with SPFX, i use jquery ajax but i haven't response (inclusive i haven't error descripction).

$.ajax("http://www.mindicador.cl/api",{  
  headers: { Accept: "application/json;odata=verbose" },  
  async:true,  
  success: function (data) {  
      var items = data.d.results;  
      },error: function (data,a , b) {  
        alert("An error occurred. Please try again.");  
      }  
  }); 

i use WebRequestInfo too (like add-ins) but it response 404.

const context: SP.ClientContext = new SP.ClientContext(this.context.pageContext.web.absoluteUrl);
let request : SP.WebRequestInfo = new SP.WebRequestInfo;
request.set_url("http://www.mindicador.cl/api");
request.set_method("GET");
request.set_headers({ "Accept": "application/json;odata=verbose" });
var response : SP.WebResponseInfo = SP.WebProxy.invoke(context, request);
context.executeQueryAsync(() => {
  console.log(response.get_statusCode() + "," + response.get_headers());
}, (sender, args) => {
  console.log(args.get_message());
});

There is a mistake in the code or there are an another way to consume remote endpoints in SPFX? thanks!

1

Use PNP js instead,

This might help you:

calling-external-apis-securely-from-sharepoint-framework

  • I have to use this way to consume the api. thx! – Bruno Palma Dec 7 '17 at 19:18
1

This is a public API that isn't secured so you should be able to call it using the standard HttpClient that's a part of the SharePoint Framework. In your web part you should be able to do, something similar to:

this.context.httpClient
    .get('http://www.mindicador.cl/api', HttpClient.configurations.v1)
    .then((res: HttpClientResponse): Promise<any> => {
      return res.json();
    })
    .then((data: any): void => {
      // process your data here
    }, (err: any): void => {
      // handle error here
    });

For this code to work you have to include the following import statement:

import { HttpClient, HttpClientResponse } from '@microsoft/sp-http';
  • i have troubles with cors and sharepoint, i have to use azure function to secure the api, then i havent problems. thx! – Bruno Palma Dec 7 '17 at 19:15
  • It's ridiculous you have to use Azure functions. So much more hastle just to make a simple api call. @BrunoPalma have you found any other way? waldek is Azure Functions the only option? I'm trying to get Slack's API working but I'm also getting CORS errors. – Batman Dec 10 '18 at 8:48
0

The solution to consume apis are in the link that mohd tahir said. i use the following code on index.js (on the azure js function )

var request = require('request');
module.exports = function (context, req) {
context.log('JavaScript HTTP trigger function processed a request.');
request('http://www.mindicador.cl/api', function (error, response, body) {

    if (error) {
        context.log(error);
    }
    if (!error && response.statusCode == 200) {
        context.res = {
            body: body,
            headers: {
                "Access-Control-Allow-Credentials" : false,
                "Access-Control-Allow-Origin" : "contoso.sharepoint.com",
                "Access-Control-Allow-Methods": "GET, OPTIONS",
                "Access-Control-Allow-Headers" : "Content-Type, Set-Cookie, application/json",
                "Access-Control-Max-Age" : "86400"
            }
        };
        context.log(body);
    }
    context.done();
});
};

and add a package.json file

{
 "name": "API MiIndicadores Secure",
 "version": "1.0.0",
 "description": "Asegurar api MiIndicadores",
 "main": "index.js",
 "author": "bpalma",
 "private": true,
 "dependencies": {
   "require": "^2.4.20"
 }
}

then npm install, then use the Waldek Mastykarz answer to consume the azure function changing the url. thx both!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.