簡體   English   中英

節點js控制台和端點返回對象但無法作為json對象獲取

[英]node js console and endpoint returning object but cannot fetch as json object

我正在將 NLP 情感分析 API 用於在線課程項目。 我想我已經接近了,但我無法完成最后一步。 目前,當我發送要由 API 調用分析的 URL 時,我會在服務器控制台中獲取返回的對象,然后將數據發送到路由 /sentiment。 然后我有一個函數,我試圖從 /sentiment 獲取數據並更新頁面以顯示結果。 #hen 我嘗試從 /sentiment 獲取數據我得到一個空對象並且我的頁面更新為 undefineds。 當我轉到 /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) {
            JSON.stringify(response);
            projectData = response;
            console.log(projectData);
        }else{
            console.log(error)
        }
    })
};

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

function getSentiment(req, res){
    console.log(req.body);
    projectData = req.body;
    console.log(projectData);
    res.status(200).send(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.get('/sentiment', getData);

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

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

function getURL(req, res){
    console.log(req.body);
    url = req.body.data;
    console.log(url)
    apiCall(url)
}

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('/postURL', url)
    updateUI();
};

export { handleSubmit }

更新UI.js:

const updateUI = async () =>{
    const res = await fetch('/sentiment');
    try {
        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.subjectivity;
        document.getElementById("subjectivityConfidence").innerHTML = allData.subjectivity_confidence;
        return allData
    } catch(error) {
        console.log(error)
    }
};

export { updateUI }

我不知道為什么我在服務器端和 /sentiment 看到所有數據,但是當我嘗試在 updateUI 函數中獲取它時只得到一個空對象。 任何幫助都會非常非常感激。

非常感謝,邁克爾

您需要提供到服務器的完整路徑,例如

const res = await fetch('http://localhost:8000/sentiment');

或者嘗試移動

app.get('/sentiment', getData);

以上

app.route('/')

更新

const allData = await res.json(); // problem is here

嘗試

 console.log(res.data); // here you will see what you are getting.
 const allData = await res.data; // You might will be having the response here


你這可能會有所幫助。

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

JSON.stringify + res.send = Content-Type "text/html"

您的客戶端應用程序無法將其反序列化為 JSON。 你的問題是你是JSON.stringify -ing 它並通過res.send從服務器發送它。

此組合設置了錯誤的 Content-Type 標頭。

閱讀res.send的 Express API 文檔:

當參數為 String 時,該方法將 Content-Type 設置為“text/html”:

所以你可以在瀏覽器中看到它,因為瀏覽器正在呈現文本,但客戶端應用程序無法使用res.json()反序列化它,因為內容類型沒有從服務器正確設置。

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

它需要設置為application/json

這是你需要做的

  1. 將您的端點更改為sendJson
  2. 不要JSON.stringify它。 發送對象並讓 Express 序列化它。
function getData(req, res){
    // JSON.stringify({projectData}); <- don't stringify it
    res.sendJson(projectData) // <- use sendJSON
    console.log(projectData)
};

閱讀res.json的 Express API 文檔:

發送 JSON 響應。 此方法發送一個響應(具有正確的內容類型),該響應是使用 JSON.stringify() 轉換為 JSON 字符串的參數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM