简体   繁体   中英

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

I'm using the weatherstack API and want to send the current temperature of a given city to a simple form in html using the POST method in express (or axios, if possible). I tried to use the GET method in axios to consume the API and the POST method in express to send the result once the user enters the city they want in the search bar. The code is the following:

app.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");
});

The website

<!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>

But when I run the server I get this error:

错误

How can I solve that?

Axios return the AxiosResponse object.

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

the content of your response is within the 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>`
)

Or

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

I tested this code, and it works fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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