A
A
Alexander Ivanov2018-02-08 16:45:47
React
Alexander Ivanov, 2018-02-08 16:45:47

How to use axios-jsonp in react?

A piece of a pluggable component

import React, { Component } from 'react';
import Aaxios from 'axios';
import jsonpAdapter from 'axios-jsonp'; 

export default class Vk extends React.Component {
    state = {
        persons: []
    };
//подбоный вариант всё ещё ругается на Access-Control-Allow-Origin
    componentDidMount() {
        Aaxios.get(`https://api.vk.com/method/photos.search?q=210700286&v=5.52`,{ adapter: jsonpAdapter })
            .then(res => {
                const persons = res.data;
                this.setState({ persons });
            })
    }

    render() {
        return (
            <ul>
                { this.state.persons.map(person => <li>{person.name}</li>)}
            </ul>
        )
    }
}

node
const
    express = require('express'),
    serve = require('express-static'),
    cors = require('cors'),
    app = express();

app.get('/', (req, res) => {
    res.sendfile(__dirname + '/public/index.html');
});

app.use(serve(__dirname + '/public/',{
    setHeaders: function setHeaders(res) {
        res.header('Access-Control-Allow-Origin', '*');
        res.header('Access-Control-Allow-Methods', 'GET');
        res.header('Access-Control-Allow-Headers', 'Content-Type');
    }
}));

app.listen(3000, () => {console.log(':3000')});

axios-jsonp - needed for Access-Control-Allow-Origin
to work axios - most preferred for JSON yes quite generic for non-JQ type JS

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Ivanov, 2018-02-08
@cimonlebedev

axios-jsonp-pro

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question