首页 > 解决方案 > 节点js更新。获取不工作。终端显示数据,浏览器控制台不显示

问题描述

我一直在为一个在线课程的项目而苦苦挣扎。我正在尝试进行 API 调用,然后获取数据,但它不起作用。我可以在我的服务器终端中看到数据,当我转到端点/sentiment 时,我也可以看到所有数据。如果我转到端点,然后返回带有表单的页面并重新提交,我会在控制台中看到所有数据并且页面已正确更新。问题是没有立即获取和返回数据。这是相关代码:

index.js(服务器端):

var path = require('path');
const express = require('express');
const mockAPIResponse = require('./mockAPI.js');
const dotenv = require('dotenv');
const bodyParser = require('body-parser');

const app = express()
app.use(express.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
const cors = require('cors');
app.use(cors());

app.use(express.static('dist'))

dotenv.config();
console.log(`Your API key is ${process.env.API_ID}`);

console.log(__dirname)

projectData = {};

url = {};

const AYLIENTextAPI = require('aylien_textapi');

let textapi = new AYLIENTextAPI({
    application_id: process.env.API_ID,
    application_key: process.env.API_KEY,
})


let apiCall = async (url) => {
    textapi.sentiment({
        'url': url
    }, function(error, response) {
        if (error === null) {
            projectData = response;
            console.log(projectData);
        }else{
            console.log(error)
        }
    })
};

app.route('/sentiment')
    .get(getData)
    .post(getURL)


function getData(req, res){
    //JSON.stringify(projectData);
    res.status(200).send(projectData)
    console.log(projectData)
};

app.route('/')
    .get(function (req, res) {
        console.log(process.env);
        res.sendFile('dist/index.html', { root: __dirname + '/,'})
        res.status(200).json(projectData)
    })
    .post(getSentiment);

function getSentiment(req, res){
    console.log(req.body);
    projectData = req.body;
    console.log(projectData);
    res.status(200).json(projectData);
};

const port = 8000;

// designates what port the app will listen to for incoming requests
app.listen(port, function () {
    console.log(`Example app listening on ${port}`)
})



app.post('/postURL', getURL);

function getURL(req, res){
    console.log(req.body);
    url = req.body.data;
    console.log(url)
    apiCall(url)
    .then(res.status(200).json(projectData))
}

我试过了

res.status(200).json(projectData)

res.status(200).send(projectData)

并且都在浏览器控制台中返回一个未定义的对象。

formHandler.js:

import { postURL } from "./postURL"
import { updateUI } from "./updateUI"



function handleSubmit(event) {
    event.preventDefault()

    // check what text was put into the form field
    let url = document.getElementById('URL').value
    postURL('/sentiment', url)
    .then(updateUI());
};

export { handleSubmit }

我的导师告诉我要改变

.then(updateUI())

.then(updateUI)

但这似乎并没有调用该函数。

我也试过:

postURL('/postURL', url)

并得到相同的结果。

postURL.js:

import { apiCall } from "./apiCall"
import { updateUI } from "./updateUI"

let postURL = async(url = '', data = {})=>{
    console.log(data);
    let response = await fetch(url, {
        method: 'POST',
        credentials: 'same-origin',
        headers: {
            "Content-Type": 'application/json',
        },
        body: JSON.stringify( { data} ),
    });
    try {
        updateUI()
    }catch(error){
        console.log("error", error);
    }
}

export { postURL }

更新UI.js:

const updateUI = async () =>{
    const res = await fetch('/sentiment');
    console.log(res);
    try {
        console.log(res.data)
        const allData = await res.json();
        console.log(allData)
        document.getElementById("polarity").innerHTML = allData.polarity;
        document.getElementById("polarityConfidence").innerHTML = allData.polarity_confidence;
        document.getElementById("subjectivity").innerHTML = allData.polarity;
        document.getElementById("subjectivityConfidence").innerHTML = allData.polarity_confidence;
        return allData
    } catch(error) {
        console.log(error)
    }
};

export { updateUI }

console.log(res) 返回:

Response {type: "basic", url: "http://localhost:8000/sentiment", redirected: false, status: 200, ok: true, …}
type: "basic"
url: "http://localhost:8000/sentiment"
redirected: false
status: 200
ok: true
statusText: "OK"
headers: Headers {}
body: (...)
bodyUsed: true
__proto__: Response

我真的很想弄清楚为什么我可以在服务器终端中看到数据,以及当我在浏览器中转到 /sentiment 时,但无论我尝试什么,我都无法从端点获取数据。我无法告诉您在此问题上的任何帮助,我将不胜感激。

非常感谢,迈克尔

标签: javascriptnode.jsexpress

解决方案


我知道了。我需要将 apiCall 函数直接移动到我的 /postURL 路由中。

app.post('/postURL', getURL);

function getURL(req, res){
    console.log(req.body);
    url = req.body.data;
    console.log(url)
    textapi.sentiment({
        'url': url
    }, function(error, response) {
        if (error === null) {
            projectData = response;
            console.log(projectData);
            res.send(projectData)
        }else{
            projectData = {polarity: 'enter a valid URL', polarity_confidence: 'enter a valid URL', subjectivity: 'enter a valid URL', subjectivity_confidence: 'enter a valid URL'}
            console.log(error)
            res.send(projectData)
        }
    })
}

推荐阅读