简体   繁体   English

为什么从本地文件中要求猫鼬不起作用?

[英]why is Requiring mongoose from local file is not working?

So I have the code所以我有代码

Directory/app/script.js:-目录/app/script.js:-

// MongoDb
// Connect to MongoDB through Mongoose
const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost:27012/profiles')

// Requiring the Schemas
const SignIn = require('MongoDb/Models/profiles.js')

console.log(SignIn)

So what is wrong in the code.那么代码有什么问题。 The console in the web says that require is not defined.网络上的控制台说 require 没有定义。 Can you help me with how to go about it.你能帮我解决怎么做吗?

There are two reasons you might get this error.您可能会收到此错误的原因有两个。 Since you said既然你说

The console in the web says网络上的控制台说

I expect it is the first reason in your code我希望这是您代码中的第一个原因

You are running the code in a web browser您正在 Web 浏览器中运行代码

Node.js is a stand-alone environment for running JavaScript. Node.js 是一个运行 JavaScript 的独立环境。 It is not a browser extension.它不是浏览器扩展。

To run Node.js code, save it in a file with a .js file extension, then run it with:要运行 Node.js 代码,请将其保存在具有.js文件扩展名的文件中,然后使用以下命令运行它:

node yourFile.js

If you want Node.js code and browser code to interact then the typical way is to write a server in Node.js that hosts a web service.如果您希望 Node.js 代码和浏览器代码交互,那么典型的方法是在 Node.js 中编写一个服务器来托管 Web 服务。 Express.js is a popular way to do this. Express.js 是一种流行的方法。 You can then use Ajax to make HTTP requests to that web service.然后,您可以使用 Ajax 向该 Web 服务发出 HTTP 请求。

For bi-directional communication (as opposed to the request/response of Ajax) look at Socket.io.对于双向通信(与 Ajax 的请求/响应相反),请查看 Socket.io。

You are using ECMAScript modules您正在使用 ECMAScript 模块

Node originally used CommonJS modules which use module.exports and require . Node 最初使用 CommonJS 模块,这些模块使用module.exportsrequire

Recent versions also support ECMAScript modules which use export and import .最近的版本还支持使用exportimport的 ECMAScript 模块。

Either switch to using import instead of require or change your configuration to use CommonJS modules.切换到使用import而不是require更改配置以使用 CommonJS 模块。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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