【问题标题】:Passing input to predefined URL path parameter in js在js中将输入传递给预定义的URL路径参数
【发布时间】:2018-02-11 15:22:03
【问题描述】:

我是 react、redux 和 axios 的新手。我正在使用该库来调用后端。我想使用/api/posts/:id 之类的模板提出请求。阅读文档后,似乎 axios 通过使用 params 属性仅支持查询字符串参数。除了我自己将参数添加到 url 的明显解决方案之外,是否有任何解决方案可以使用库传递参数?

【问题讨论】:

  • 使用params 对象有什么问题?
  • 您可以在 URL 上附加或使用参数github.com/axios/axios#example
  • @DragoşPaulMarinescu params 对象用于查询字符串参数。请求看起来像api/posts?id=someid

标签: javascript node.js axios


【解决方案1】:

我的理解是您想发送到api/posts/:id 而不是像api/posts?id=someid 这样的查询字符串,如果是这种情况,那么您可以自己创建网址并点击它:

const url = 'api/posts/' + id;

axios.get(url)
.then(function (response) {
    console.log(response);
})
.catch(function (error) {
    console.log(error);
});

【讨论】:

  • 谢谢,但正如我在问题中所说,我不想自己构建网址。
  • 我不确定是否有任何库提供该功能。
  • 有角度体验这个功能对我来说有点常见。
  • 如果您正在为您的应用程序创建或定义路由,那么只有您可以简单地定义 /api/posts/:id 并配置您需要呈现的任何 html,但如果您正在发出 ajax 请求,那么我不认为它会自行构建。
【解决方案2】:

不幸的是,在撰写本文时,js 中还没有按对象进行原生预定义字符串格式化。您将不得不依赖字符串模板库,例如 lodash.template、mustache.js、handlebar.js。

例子:

/**
 * Formatting string using lodash
 * install it by:
 * $ npm i lodash.template
 */
const template = require('lodash.template');

const compiled = template('/api/posts/<%= id %>/other/filter/<%= encodeURIComponent(name) %>/<%= nested.id %>');
let output = compiled({id: "12345678", name: "<good bot>", nested: {id: "777"}});
console.log(output); //output: "/api/posts/12345678/other/filter/<good bot>/777"

但在您的情况下,这会带来一个问题:lodash 不提供转义 HTML 以外的字符串的选项,您必须在模板中转义它(如上面代码中的 encodeURIComponent(name) 所示),或者你的对象的价值。

另一个选择是使用 mustache.js,覆盖 mustache HTML 的转义函数:

/**
 * Formatting string using mustache
 * install it by:
 * $ npm install mustache --save
 */
const mustache = require('mustache');

mustache.escape = (value) => encodeURIComponent(value);
const output = mustache.render(
    '/api/posts/{{id}}/other/filter/{{name}}/{{nested.id}}',
    {id: "12345678", name: "<good bot>", nested: {id: "777"}}
);

console.log(output); //output: "/api/posts/12345678/other/filter/%3Cgood%20bot%3E/777"

那么你现在可以将output 传递给 axios。

【讨论】:

    【解决方案3】:

    您可以在 axios 中将 GET 参数作为第二个参数发送。

    语法:

    axios.get(url[, config])
    

    一个例子:

    axios.get('/api/posts/', {
      params: {
        id: 12345
      }
    })
    .then(function (response) {
      console.log(response);
    })
    .catch(function (error) {
      console.log(error);
    });
    

    【讨论】:

    • 您的方法不会将 id 附加到 url(将其作为 url 参数传递),而是将其附加到请求查询参数中,从而产生如下请求:/api/posts?id=12345
    猜你喜欢
    • 2022-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-14
    • 2021-04-24
    • 2016-02-07
    • 2011-10-12
    相关资源
    最近更新 更多