Axios VueJS和开放API

ubof19bj  于 2023-02-04  发布在  iOS
关注(0)|答案(3)|浏览(198)

我正在尝试从一个API获取数据。但是当我在浏览器上直接使用失眠症时,它是可以的。
当我在代码中使用axios时,我遇到了这个错误:阻止多来源请求(跨来源请求):"同源"策略不允许查询远程资源....
我的代码

const axiosInstance = axios.create({
    baseURL : 'https://trefle.io/api/v1/plants?token=********',
    mode: 'no-cors',
    withCredentials: false,
    credentials: 'same-origin',
    headers : {
        'Access-Control-Allow-Origin': '*',
        'Content-Type': 'application/json',
    }
})

async getPlantsList(context)
        {
            try{            
                const response = await axiosInstance.get();

                console.log('2', response.data);

            } catch(error){
                console.log('error', error);
            }
        }

我需要帮助,我在网上搜索,但我没有找到解决方案。
谢谢你的帮助
在axios示例中添加标题

ztyzrc3y

ztyzrc3y1#

几个问题:

  1. Access-Control-Allow-Origin header在您的 * request * 中没有位置,因为它是一个 * response * 报头。
    1.如果你想让你的客户端访问响应,你不能使用no-cors模式,你必须使用cors模式(这是跨源请求的默认模式)。
    1.因为所讨论的资源似乎不允许任何请求头文件,除了 * CORS安全列表的请求头文件 *,您将无法在请求中包含Content-Type头文件。但请注意,所讨论的请求是GET,对于它来说,包含Content-Type头文件是没有意义的。因为GET请求并不意味着有一个主体,所以只需从请求中删除该标头即可。
    如果你解决了所有三个问题,它应该工作。
cl25kdpy

cl25kdpy2#

不需要设置cors选项
我将通过axios调用显示两个选项。两者的结果相同
选项1:使用create()

const axios = require("axios")

const token ='<your token>'
const api = axios.create({baseURL: `https://trefle.io/api/v1/plants/?token=${token}`});

try {
    api.get().then((results) => {
        for (plant of results.data.data) { 
            console.log(JSON.stringify(plant))
        }
    })
} catch (error) {
    console.log(error)
}

选项2:不创建()

const axios = require("axios")

const getPlants = async () => {
    try {
        const token ='<your token>'
        const response = await axios.get(`https://trefle.io/api/v1/plants?token=${token}`);
        return Promise.resolve(response.data);
    } catch (error) {
        return Promise.reject(error);
    }
}

getPlants()
    .then(plants => {
        for (plant of plants.data) { 
            console.log(JSON.stringify(plant))
        }
}).catch(error => console.log(error));

结果1

$ node get-option1.js
{"id":77116,"common_name":"Evergreen oak","slug":"quercus-rotundifolia","scientific_name":"Quercus rotundifolia","year":1785,"bibliography":"Encycl. 1: 723 (1785)","author":"Lam.","status":"accepted","rank":"species","family_common_name":null,"genus_id":3519,"image_url":"https://d2seqvvyy3b8p2.cloudfront.net/40ab8e7cdddbe3e78a581b84efa4e893.jpg","synonyms":["Quercus ilex var. oleoides","Quercus ilex subvar. rotundifolia","Quercus ilex f. macrophylla","Quercus ilex f. oleoides","Quercus ilex var. calicina","Quercus ilex subsp. rotundifolia","Quercus lyauteyi","Quercus ballota var. rotundifolia","Quercus ilex f. brevicupulata","Quercus ilex subvar. major","Quercus ilex var. pendula","Quercus rotundifolia f. dolichocalyx","Quercus calicina","Quercus rotundifolia f. pilosella","Quercus rotundifolia f. macrocarpa","Quercus ilex var. rotundifolia","Quercus sugaro","Quercus ilex subvar. pendula","Quercus ilex f. pendula","Quercus ilex f. ballota","Quercus ilex f. rotundifolia","Quercus ilex subvar. minor","Quercus ballota","Quercus ilex var. ballota","Quercus ilex f. calicina","Quercus ilex var. microcarpa","Quercus rotundifolia f. calicina","Quercus ilex f. macrocarpa","Quercus rotundifolia f. brevicupulata","Quercus rotundifolia var. macrocarpa","Quercus ilex var. brevicupulata","Quercus ilex subsp. ballota","Quercus ilex var. dolichocalyx","Quercus rotundifolia var. pilosella","Quercus rotundifolia var. brevicupulata","Quercus rotundifolia subsp. maghrebiana"],"genus":"Quercus","family":"Fagaceae","links":{"self":"/api/v1/species/quercus-rotundifolia","plant":"/api/v1/plants/quercus-rotundifolia","genus":"/api/v1/genus/quercus"}}

... cut off

结果二

$ node get-option2.js
{"id":77116,"common_name":"Evergreen oak","slug":"quercus-rotundifolia","scientific_name":"Quercus rotundifolia","year":1785,"bibliography":"Encycl. 1: 723 (1785)","author":"Lam.","status":"accepted","rank":"species","family_common_name":null,"genus_id":3519,"image_url":"https://d2seqvvyy3b8p2.cloudfront.net/40ab8e7cdddbe3e78a581b84efa4e893.jpg","synonyms":["Quercus ilex var. oleoides","Quercus ilex subvar. rotundifolia","Quercus ilex f. macrophylla","Quercus ilex f. oleoides","Quercus ilex var. calicina","Quercus ilex subsp. rotundifolia","Quercus lyauteyi","Quercus ballota var. rotundifolia","Quercus ilex f. brevicupulata","Quercus ilex subvar. major","Quercus ilex var. pendula","Quercus rotundifolia f. dolichocalyx","Quercus calicina","Quercus rotundifolia f. pilosella","Quercus rotundifolia f. macrocarpa","Quercus ilex var. rotundifolia","Quercus sugaro","Quercus ilex subvar. pendula","Quercus ilex f. pendula","Quercus ilex f. ballota","Quercus ilex f. rotundifolia","Quercus ilex subvar. minor","Quercus ballota","Quercus ilex var. ballota","Quercus ilex f. calicina","Quercus ilex var. microcarpa","Quercus rotundifolia f. calicina","Quercus ilex f. macrocarpa","Quercus rotundifolia f. brevicupulata","Quercus rotundifolia var. macrocarpa","Quercus ilex var. brevicupulata","Quercus ilex subsp. ballota","Quercus ilex var. dolichocalyx","Quercus rotundifolia var. pilosella","Quercus rotundifolia var. brevicupulata","Quercus rotundifolia subsp. maghrebiana"],"genus":"Quercus","family":"Fagaceae","links":{"self":"/api/v1/species/quercus-rotundifolia","plant":"/api/v1/plants/quercus-rotundifolia","genus":"/api/v1/genus/quercus"}}
... cut off

o0lyfsai

o0lyfsai3#

有人能花点时间解释一下为什么我的代码不起作用吗?

const axiosInstance = axios.create({
    baseURL : `https://trefle.io/api/v1/plants?token=${token}`,
})

actions:{
        async getPlantsList(context)
        {
            try{
                console.log(axiosInstance);        
                const response = await axiosInstance.get();

                console.log('2', response.data);
                context.commit();

            } catch(error){
                console.log('error', error);
            }
        }

相关问题