提问者:小点点

在URL中使用对象参数发布动作API


我有一个API,其中一些参数需要在URL中给出。我的api url的示例如下:https://www.server.com/api/actions/execute?auth_type=apikey

我的代码现在是什么样子

register = async () => {
    let data = {"Name":this.state.name, "Email":this.state.email}
    data = JSON.stringify(data)

    let URL = 'https://www.server.com/api/actions/execute?auth_type=apikey&data=';

    fetch(URL, {
      method: 'POST',
      headers: new Headers({
        'Content-Type': 'application/json'
      }),
      body: data
      })
      .then((response) => response.text())
      .then((responseText) => {
        alert(responseText);
      })
      .catch((error) => {
          console.error(error);
    });
  }

我在设备上得到的响应:

{"code":"succes","details":{"userMessage":["java.lang.Object@2e56000c"],"output_type":void","id:"20620000000018001"},"message":"function executed succesfully"}

当我在postman中测试它时,这一切都可以正常工作,但我无法让它在React-Native中工作。我已经尝试过'Content-Type':'application/x-wew-form-urlencoded'之类的东西。


共2个答案

匿名用户

首先从url安装包axioshttps://www.npmjs.com/package/react-native-axios然后创建两个服务来处理get和post请求,以便您可以重用它们

获取服务. js

import axios from 'axios'; 
let constant = {
    baseurl:'https://www.sampleurl.com/'
};
let config = {

    headers: {
    'Content-Type': 'multipart/form-data',
    'Accept': 'application/json'
    }
};

export const GetService = (data,Path,jwtKey) => {
    if(jwtKey != ''){
        axios.defaults.headers.common['Authorization'] = 'Bearer '+jwtKey;
    }

    try{
        return axios.get(
                            constant.baseUrl+'api/'+Path, 
                            data, 
                            config
                        );
    }catch(error){
        console.warn(error);
    }
}    

PostService. js

import axios from 'axios'; 
let constant = {
    baseurl:'https://www.sampleurl.com/'
};
let config = {

    headers: {
    'Content-Type': 'multipart/form-data',
    'Accept': 'application/json'
    }
};

export const PostService = (data,Path,jwtKey) => {
    if(jwtKey != ''){
        axios.defaults.headers.common['Authorization'] = 'Bearer '+jwtKey;
    }

    try{
        return axios.post(
                            constant.baseUrl+'api/'+Path, 
                            data, 
                            config
                        );
    }catch(error){
        console.warn(error);
    }
}

下面给出了使用get和post服务的示例代码

import { PostService } from './PostService';
import { GetService } from './GetService';


let uploadData = new FormData();
uploadData.append('key1', this.state.value1);
uploadData.append('key2', this.state.value2);
//uploadData.append('uploads', { type: data.mime, uri: data.path, name: "samples" });

let jwtKey = ''; // Authentication key can be added here
PostService(uploadData, 'postUser.php', jwtKey).then((resp) => {
this.setState({ uploading: false });
    // resp.data will contain json data from server
}).catch(err => {
    // handle error here
});



GetService({}, 'getUser.php?uid='+uid, jwtKey).then((resp) => {
    // resp.data will contain json data from server
}).catch(err => {
    // handle error here
});

匿名用户

如果你需要通过URL传递参数,你应该使用GET,如果你使用POST,那么参数应该在body中传递