javascript - 无法发送除
问题描述
如果我将“< h1 >”更改为任何其他 HTML 标记,例如“< h2 > 或 < p >”,则无法呈现它们。我不知道出了什么问题。
const express = require("express");
const https = require("https");
const app = express();
// home page
app.get("/", function (req, res) {
res.sendFile(__dirname + "/index.html");
});
app.post("/", function (req, res) {
const queryCity = "London";
// const queryCity = String(req.body.cityName);
const apiKey = "lorem";
const url =
"https://api.openweathermap.org/data/2.5/weather?q=" +
queryCity +
"&appid=" +
apiKey +
"&units=metric";
https.get(url, function (response) {
response.on("data", function (data) {
const weatherData = JSON.parse(data);
const temp = weatherData.main.temp;
const feel = weatherData.main.feels_like;
const weatherIcon = weatherData.weather[0].icon;
const iconUrl =
"https://openweathermap.org/img/wn/" + weatherIcon + "@2x.png";
res.write(
"<h1>Temperature in " + queryCity + " is " + temp + "deg Celsius.</h1>"
);
res.write("It feels like " + feel + "deg Celsius.");
res.write("<img src=" + iconUrl + ">");
res.send(); // there can only be one res.send()
});
});
});
// server port
app.listen(3000, function () {
console.log("Server live on port 3000");
});
解决方案
此代码永远不会失败:
var express = require('express');
var app = express();
app.get('/', function(req, res) {
res.type('text/html');
res.send('<h1>I am html</h1>');
});
app.listen(process.env.PORT || 8080);
尝试使用此基本代码测试您的 html 生成,以确保错误不是 nodejs 问题。
另一个提示:
- 替换
res.write
为res.send
喜欢我的示例 - 不要
res.write
多次调用,只需一次发送以前用您的 html 行创建的字符串 - 将内容类型 text/html 添加到您的响应中
推荐阅读
- android - ConcurrentModificationException - 如何修复?
- java - CSS 在运行程序时不起作用,但在我不运行时它确实起作用
- tomcat - 具有受保护端点的 SPARQL SERVICE
- python - Python 列表说明:无法直接赋值
- arrays - matlab如何将字符串存储到数组中
- bash - 将循环中的参数附加到 CLI 命令
- python-3.x - 有效地绘制具有“最大多样性”的组合
- java - 将所有 JSON 值转换为字符串
- android - 如何像在 Android Studio 中一样在 IntelliJ 中使用 Instant Run 按钮?
- java - Array2d java错误