Я просматриваю грубое руководство по node.js и mongodb Atlas, и когда я пытаюсь отправить запрос на создание пользователя на сервер, я получаю ошибку Cors-источника.
Я поставил требование cors, и app.use
в моем server.js
есть что-то еще, что мне нужно сделать?
Вот ошибка:
Блокировка перекрестного запроса: та же политика происхождения запрещает чтение удаленного ресурса на http://localhost:5000/users/. (причина: запрос CORS не выполнен).
Server.js
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
require('dotenv').config();
const app = express();
const port = process.env.PORT || 5000;
app.use(cors());
app.use(express.json());
const uri = process.env.ATLAS_URI;
mongoose.connect(uri, { useNewUrlParser: true, useCreateIndex: true });
const connection = mongoose.connection;
connection.once('open', () => {
console.log("MongoDB database connection established successfully");
})
const exercisesRouter = require('./routes/exercises');
const usersRouter = require('./routes/users');
app.use('/exercises', exercisesRouter);
app.use('/users', usersRouter);
app.listen(port, () => {
console.log(`Server is running on port: ${port}`);
});
users.js
const router = require('express').Router();
let User = require('../models/user.model');
router.route('/').get((req, res) => {
User.find()
.then(users => res.json(users))
.catch(err => res.status(400).json('Error: ' + err));
});
router.route('/add').post((req, res) => {
const username = req.body.username;
const newUser = new User({username});
newUser.save()
.then(() => res.json('User added!'))
.catch(err => res.status(400).json('Error: ' + err));
});
module.exports = router;
Вот что я получаю в браузере:
{username: "wwewe"}
username: "wwewe"
__proto__:
constructor: ƒ Object()
hasOwnProperty: ƒ hasOwnProperty()
isPrototypeOf: ƒ isPrototypeOf()
propertyIsEnumerable: ƒ propertyIsEnumerable()
toLocaleString: ƒ toLocaleString()
toString: ƒ toString()
valueOf: ƒ valueOf()
__defineGetter__: ƒ __defineGetter__()
__defineSetter__: ƒ __defineSetter__()
__lookupGetter__: ƒ __lookupGetter__()
__lookupSetter__: ƒ __lookupSetter__()
get __proto__: ƒ __proto__()
set __proto__: ƒ __proto__()
xhr.js:166 OPTIONS http://localhost:5000/users/add
net::ERR_CONNECTION_REFUSED
dispatchXhrRequest @ xhr.js:166
xhrAdapter @ xhr.js:16
dispatchRequest @ dispatchRequest.js:49
Promise.then (async)
request @ Axios.js:56
Axios.<computed> @ Axios.js:80
wrap @ bind.js:11
onSubmit @ create-user.component.js:31
callCallback @ react-dom.development.js:363
invokeGuardedCallbackDev @ react-dom.development.js:412
invokeGuardedCallback @ react-dom.development.js:466
invokeGuardedCallbackAndCatchFirstError @ react-dom.development.js:481
executeDispatch @ react-dom.development.js:614
executeDispatchesInOrder @ react-dom.development.js:639
executeDispatchesAndRelease @ react-dom.development.js:744
executeDispatchesAndReleaseTopLevel @ react-dom.development.js:753
forEachAccumulated @ react-dom.development.js:725
runEventsInBatch @ react-dom.development.js:770
runExtractedPluginEventsInBatch @ react-dom.development.js:916
handleTopLevel @ react-dom.development.js:6171
batchedEventUpdates @ react-dom.development.js:2422
dispatchEventForPluginEventSystem @ react-dom.development.js:6271
dispatchEvent @ react-dom.development.js:6301
unstable_runWithPriority @ scheduler.development.js:674
runWithPriority$2 @ react-dom.development.js:11834
discreteUpdates$1 @ react-dom.development.js:22935
discreteUpdates @ react-dom.development.js:2440