webpack 您好,我收到错误“语法错误:意外的标记“〈”,“〈!DOCTYPE..."不是有效的JSON”

whhtz7ly  于 2022-11-13  发布在  Webpack
关注(0)|答案(1)|浏览(148)

嗨,我创建了一个简单的应用程序,它使用三个api来获取数据并在网页中适当地呈现数据。它使用节点、express服务器、body-parser和cors作为中间件。我还编译了webpack中的所有代码,并运行了出现错误的webpack dev-server。下面是我的server.js:

// Setup empty JS object to act as endpoint for all routes
cityData = {};
weatherData = {};
picturesData = {};

// Require Express to run server and routes
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');

// Start up an instance of app
const app = express();

/* Middleware*/
//Here we are configuring express to use body-parser as middle-ware.
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

// Cors for cross origin allowance
app.use(cors())
// Initialize the main project folder
app.use(express.static('../website/client'));

app.get("/all", function sendData(req, res) {
    res.send(cityData);
})

app.get("/allWeather", function sendWeather(req, res) {
    res.send(weatherData);
})

app.get("/allPictures", function sendPictures(req, res) {
    res.send(picturesData);
})

app.post("/addWeather", (req, res) => {
    weatherData['temp'] = req.body.temp;
    res.send(weatherData);
})

app.post("/addPicture", (req, res) => {
    picturesData['pic'] = req.body.pic;
    res.send(picturesData);
})

// Setup Server
app.listen(3000, () => {
    console.log("App listening on port 3000")
    console.log("Go to http://localhost:3000")
})

下面是我的app.js:

const geoURL = "http://api.geonames.org/searchJSON?";
const geoUsername = `rohanasif1990`;
const weatherURL = "https://api.weatherbit.io/v2.0/forecast/daily?"
const weatherKey = "20028a8267a24bba9a807362767bc4a7"
const pixabayKey = "30776478-ff0b8818f9bba72161ebb1731"
const pixabayURL = "https://pixabay.com/api?"

const present = new Date();

const submitBtn = document.getElementById("submitBtn");

submitBtn.addEventListener("click", (e) => {
    e.preventDefault();
    const city = document.getElementById("city").value;
    const departure = document.getElementById("date").value;
    const [depart_date, depart_time] = departure.split("T")
    const [depart_year, depart_month, depart_day] = depart_date.split("-")
    const [depart_hour, depart_minute] = depart_time.split(":")

    const future = new Date(depart_year, depart_month - 1, depart_day, depart_hour, depart_minute);

    console.log(future);
    console.log(present);
    if (city !== "" || departTime !== "") {

        document.getElementById("time").innerHTML = `Departure in ${(future - present) / 3600000 / 24} days`
        getCity(geoURL, city, geoUsername)
            .then(function (data) {
                return getWeather(weatherURL, weatherKey, data["geonames"][0]['lat'], data["geonames"][0]['lng'])
            }).then(weatherData => {
                return postWeatherData("/addWeather", { temp: weatherData['data'][0]['temp'] })
            }).then(function () {
                return receiveWeatherData()
            }).catch(function (error) {
                console.log(error);
                alert("Please enter a valid city and a valid time");
            })
        getPictures(city, pixabayURL, pixabayKey)
            .then(function (picsData) {
                return postPictureData("/addPicture", { pic: picsData['hits'][0]["webformatURL"] })
            })
            .then(function () {
                return receivePictureData()
            }).catch(function (error) {
                console.log(error);
                alert("No pictures found")
            })
    }
})

const getCity = async (geoURL, city, geoUsername) => {
    const res = await fetch(`${geoURL}q=${city}&username=${geoUsername}`);
    try {
        const cityData = await res.json();
        return cityData;
    }
    catch (error) {
        console.log("error", error);
    }
}

const postWeatherData = async (url = "", data = {}) => {
    const response = await fetch(url, {
        method: "POST",
        credentials: "same-origin",
        headers: {
            "Content-Type": "application/json",
        },
        body: JSON.stringify({
            temp: data.temp
        })
    });

    try {
        const newData = await response.json();
        return newData;
    }
    catch (error) {
        console.log(error);
    }
}

const receiveWeatherData = async () => {
    const request = await fetch("/allWeather");
    try {
        const allData = await request.json()
        document.getElementById("temp").innerHTML = "TEMPERATURE: " + allData['temp'];
    }
    catch (error) {
        console.log("error", error)
    }
}

const getWeather = async (weatherURL, weatherKey, lat, lon) => {
    const res = await fetch(`${weatherURL}&lat=${lat}&lon=${lon}&key=${weatherKey}`);
    try {
        const weatherData = await res.json();
        return weatherData;
    }
    catch (error) {
        console.log("error", error);
    }
}

const getPictures = async (city, pixabayURL, pixabayKey) => {
    const query = city.split(" ").join("+");
    const res = await fetch(`${pixabayURL}key=${pixabayKey}&q=${query}`);
    try {
        const picsData = await res.json();
        return picsData;
    }
    catch (error) {
        console.log("error", error)
    }
}

const receivePictureData = async () => {
    const request = await fetch("/allPictures");
    try {
        const allData = await request.json()
        document.getElementById("city-pic").src = allData['pic'];
    }
    catch (error) {
        console.log("error", error)
    }
}

const postPictureData = async (url = "", data = {}) => {
    const response = await fetch(url, {
        method: "POST",
        credentials: "same-origin",
        headers: {
            "Content-Type": "application/json",
        },
        body: JSON.stringify({
            pic: data.pic
        })
    });

    try {
        const newData = await response.json();
        return newData;
    }
    catch (error) {
        console.log(error);
    }
}

为了查看错误,我运行了“npm i”来安装依赖项和webpack包。然后运行“npm run build-prod”来构建项目dist文件夹。然后运行“npm run build-dev”。然后以匿名方式转到localhost:3000。当我输入一些城市名称如“伦敦”时,我得到以下错误:
screenshot of the error
我不明白为什么在第130行和第64行有错误。我是javascript新手,做过很多web开发项目,但从来没有见过这种错误。看起来发送或接收的数据不是JSON,而是一个HTML文件。我认为服务器只提供静态HTML文件,而不执行app.js中的任何代码。请看一下,请帮我解决这个问题,因为这是我的一个重要项目。

kpbpu008

kpbpu0081#

这是一个错误的页面来响应,而不是JSON。

相关问题