在URL中带有对象参数的帖子行动API[英] Post action API with object parameter within the URL

本文是小编为大家收集整理的关于在URL中带有对象参数的帖子行动API的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我有一个API,其中需要在URL中给出一些参数. 我的API URL的样子:https://www.server.com/api/actions/execute?auth_type=apikey&data={"Name": "name","Email" : "email"}

我的代码现在是什么样子

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中进行测试时,这是很好的工作,但是我无法在反应本地工作.我已经尝试了'Content-Type':'application/x-www-form-urlencoded'之类的东西.

推荐答案

首先从URL https://www. npmjs.com/package/reeact-native-axios 然后创建两个用于处理和发布请求的服务,以便您可以重复使用它们

getService.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);
    }
}    

postervice.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,如果您使用帖子,则应在body

中传递参数

本文地址:https://www.itbaoku.cn/post/1937815.html

问题描述

I've got an API where some of the parameters need to be given within the URL. Example of how my api url looks like: https://www.server.com/api/actions/execute?auth_type=apikey&data={"Name": "name","Email" : "email"}

What my code looks like right now

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);
    });
  }

The response I get on my device:

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

This is alle working fine when I test it in postman but I can't get it to work within React-Native. I've tried stuff like 'Content-Type':'application/x-www-form-urlencoded' already.

推荐答案

First install the package axios from the url https://www.npmjs.com/package/react-native-axios Then create two service for handling get and post request so that you can reuse them

GetService.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);
    }
}

Sample code for using get and post services is given below

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
});

其他推荐答案

If you need to pass parameters via URL you should use GET, if you use POST then the parameters should be passed in the body