将输入传递给js中的预定义URL路径参数

时间:2018-02-11 15:22:04

标签: javascript node.js axios

我是新手,反应,还原和axios。我正在使用该库来调用后端。我想使用/api/posts/:id等模板发出请求。在阅读文档后,似乎axios仅使用params属性支持查询字符串参数。有没有我可以使用库传递参数的解决方案,除了将参数自己添加到网址的明显解决方案?

3 个答案:

答案 0 :(得分: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);
});

答案 1 :(得分:1)

不幸的是,在撰写本文时,js中的对象没有本地预定义的字符串格式。你必须依赖字符串模板库,如lodash.template,mustache.js,handlebar.js。

示例:

import psycopg2

conn = psycopg2.connect("dbname='gis3capstone' user='postgres' password='password' host='localhost' port='5433'")
cur = conn.cursor()

cur.execute('SELECT * FROM fcc_form_477')
row = cur.fetchone()
while row:
    val2 = str(row[0])[0:4]
    # Set row[1] = val2 ??
    row = cur.fetchone()

但是在你的情况下,这会产生一个问题:lodash没有提供转义除HTML以外的字符串的选项,你必须在你的模板中将其转义(如上面代码中的/** * 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" 所示) ),或你的对象的价值。

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

encodeURIComponent(name)

然后,您现在可以将/** * 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" 传递给axios。

答案 2 :(得分:-1)

您可以在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);
});