NodeJs 服务器,无法返回数据。

huangapple go评论106阅读模式
英文:

NodeJs server, I cant return data

问题

I try to get datas from mongoDb in my nodeJs server, and i cant return my datas.I tryed to return it by res.send() but it told me that .send() is not a function so I alose tryed to just return my datas but the function is in a loop

there is my code:

require('dotenv').config();
var http = require('http');
const { MongoClient } = require('mongodb');
const client = new MongoClient(process.env.MONGO_URL);
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors())

var server = http.createServer(async function (req, res) {
    let response
    await client.connect();
    console.log('Connection OK!');
    const db = client.db('ArtisanTest')
    const collection = db.collection('phones')

   if (req.url == '/') {
        // Handle root URL
        // ...
    }
    else if (req.url == "/create") {
        // Handle create URL
        // ...
    }
    else if (req.url == "/read") {
        try {
            const read = (await collection.find()).toArray()
            response = await read
        } 
        catch (e) { throw e;}   
    }
    else if (req.url == "/update") {
        // Handle update URL
        // ...
    }
    else if (req.url == "/delet") {
        // Handle delete URL
        // ...
    }

    return response
});

server.listen(5000);

console.log('Node.js web server is running at port 5000.')

(its about my /read case)

Can someone help me please

英文:

I try to get datas from mongoDb in my nodeJs server, and i cant return my datas.I tryed to return it by res.send() but it told me that .send() is not a function so I alose tryed to just return my datas but the function is in a loop

there is my code:

require('dotenv').config();
var http = require('http');
const { MongoClient } = require('mongodb');
const client = new MongoClient(process.env.MONGO_URL);
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors())
var server = http.createServer(async function (req, res) {
let response
await client.connect();
console.log('Conenction OK!');
const db = client.db('ArtisanTest')
const collection = db.collection('phones')
if (req.url == '/') {
...
}
else if (req.url == "/create") {
...
}
else if (req.url == "/read") {
try {
const read = (await collection.find()).toArray()
response = await read
} 
catch (e) { throw e;}   
}
else if (req.url == "/update") {
...
}
else if (req.url == "/delet") {
... 
}
return response
});
server.listen(5000);
console.log('Node.js web server is running at port 5000.')

(its about my /read case)

Can someone help me please

答案1

得分: 0

这个问题是因为你声明路由的方式导致的。在这里,返回操作是同步执行的,而响应却需要等待来自数据库的响应。为了解决此问题,你可以尝试在这里返回响应。尝试以下代码:

...
    else if (req.url == "/read") {
        try {
            const read = (await collection.find()).toArray()
            response = await read
            return res.send(response)
        } 
        catch (e) { throw e;}   
    
    }
...

另外,你可能想要使用 res.json() 来返回对象。

英文:

This issue arose because of the way you are declaring the routes.
Here, the return is going synchronously while the response awaits the response from the database. For resolving the error at this instance you may try returning the response from there. Try the below code

...
    else if (req.url == "/read") {
        try {
            const read = (await collection.find()).toArray()
            response = await read
            return res.send(response)
        } 
        catch (e) { throw e;}   
    
    }
...

Also, you may want to use res.json() for returning the objects.

答案2

得分: 0

你正试图使用 node:http 服务器 outgoing message,请使用 express 服务器

const express = require('express')
const app = express()

app.get('/', (req, res) => {
  res.send('Hello World!')
})

app.listen(port, () => {
  console.log(`Example app listening on port 3000`)
})
英文:

You're trying to use node:http server outgoing message, use express server

const express = require('express')
const app = express()

app.get('/', (req, res) => {
  res.send('Hello World!')
})

app.listen(port, () => {
  console.log(`Example app listening on port 3000`)
})

huangapple
  • 本文由 发表于 2023年7月13日 19:26:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/76678852.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定