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

zazmityj  于 2022-12-28  发布在  Java
关注(0)|答案(1)|浏览(177)

我正在使用weatherstack API,并希望使用express(或axios,如果可能)中的POST方法将给定城市的当前温度发送到html中的简单表单。我尝试使用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>

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

我该怎么解决呢?

iqjalb3h

iqjalb3h1#

Axios返回AxiosResponse对象。

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

您的响应内容在data对象中。

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>`
)

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

相关问题