繁体   English   中英

如何使用 axios 发送 POST 请求以向 html 文件显示消息?

[英]How can I send a POST request to display a message to an html file using axios?

我正在使用weatherstack API并希望使用 POST 方法将给定城市的当前温度发送到 html 中的简单表格(如果可能,则为 axios)。 我尝试使用 axios 中的 GET 方法来消费 API 和 express 中的 POST 方法,以便在用户在搜索栏中输入他们想要的城市后发送结果。 代码如下:

应用程序.js

const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const axios = require('axios');

const access_key = '...'

app.use(bodyParser.urlencoded({extended: false}));

app.get('/', (req, res) => {
    res.sendFile(__dirname + '/index.html');
});

// Successful GET in the console
// axios.get(`http://api.weatherstack.com/current?access_key=${access_key}&query=Dallas`)
//     .then(response => {
//         const apiResponse = response.data;
//         console.log(`Current temperature in ${apiResponse.location.name} is ${apiResponse.current.temperature}℃`);
//     }).catch(error => {
//         console.log(error);
//     });

// ----The problem-------
app.post('/', async function (req, res) {
    const{response} = await axios(`http://api.weatherstack.com/current?access_key=${access_key}&query=${req.body.cityName}`)
    res.send(`<p>Current temperature in ${req.body.cityName} is ${response.current.temperature} ℃</p>
            <a href = '/'>Back</a>`)

});
//------------------------

app.listen({port: 4000}, () => {
    console.log("Server running on localhost:4000");
});

网站

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Weatherstack</title>
</head>
<body>
    <form action="/" method="post">
        <p>Inform the city</p>
        <input name="cityName">
        <button type="submit">Send</button>
    </form>
</body>
</html>

但是当我运行服务器时,我得到这个错误:

错误

我该如何解决?

Axios 返回AxiosResponse object。

export interface AxiosResponse<T = any, D = any> {
  data: T;
  status: number;
  statusText: string;
  headers: RawAxiosResponseHeaders | AxiosResponseHeaders;
  config: AxiosRequestConfig<D>;
  request?: any;
}

您回复的内容在data object内。

const { data } = await axios(
`http://api.weatherstack.com/current?access_key=${access_key}&query=${req.body.cityName}`
);
res.send(
`<p>Current temperature in ${req.body.cityName} is ${data.current.temperature} ℃</p><a href = '/'>Back</a>`
)

要么

const response = await axios(
`http://api.weatherstack.com/current?access_key=${access_key}&query=${req.body.cityName}`
);
res.send(
`<p>Current temperature in ${req.body.cityName} is ${response.data.current.temperature} ℃</p><a href = '/'>Back</a>`
)

我测试了这段代码,它工作正常。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM