我正在尝试使用 ES6 模板文字来表示多行字符串。下面这个效果很好:
var customer = { name: "Foo" }
var card = { amount: 7, product: "Bar", unitprice: 42 }
var message = `Hello ${customer.name},
want to buy ${card.amount} ${card.product} for
a total of ${card.amount * card.unitprice} bucks?`
然后我尝试将其应用到 URL 字符串,如下所示:
let topic = "pizza";
let url = `https://en.wikipedia.org/w/api.php?action=parse§ion=0&prop=text&format=json&page=${topic}`;
单行版本效果很好。但是当我将其更改为多行时,它不起作用:
let topic = "pizza";
let url = `https://en.wikipedia.org/w/api.php
?action=parse§ion=0&prop=text&format=json&page=${topic}`;
or
let url = `https://en.wikipedia.org/w/api.php\
?action=parse§ion=0&prop=text&format=json&page=${topic}`;
我使用此 URL 来检索数据:
let https = require("https");
https.get(url, res => {...});
谁能告诉我多行 URL 有什么问题吗?我怎样才能正确地做呢?非常感谢。
最佳答案
您的网址中包含换行符。如果 `` 旁边有换行符,则模板文字语法允许您向字符串添加换行符,因此您的 URL 中也有换行符。
console.log('\n' === `
`) // true
在进行 HTTP 调用之前对 url 执行 String.prototype.replace()
let topic = "pizza";
let url = `https://en.wikipedia.org/w/api.php
?action=parse§ion=0&prop=text&format=json&page=${topic}`;
// removes newline characters from template string
url.replace('\n', '');
// do your stuff here
let https = require("https");
https.get(url, res => {...});
或者转义模板字符串中的换行符
let topic = "pizza";
// escape the newline character
let url = `https://en.wikipedia.org/w/api.php\
?action=parse§ion=0&prop=text&format=json&page=${topic}`;
// do your stuff here
let https = require("https");
https.get(url, res => {...});
关于javascript - 这个多行 url 字符串有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49373309/