Failed to compile error
Closed this issue · 4 comments
I am getting a failed to compile error when trying to connect the database to the frontend in react. I have tried importing from server.js and index.js. Below is the complete error.
./src/server.js
Module not found: You attempted to import ../db/connection which falls outside of the project src/ directory. Relative imports outside of src/ are not supported. You can either move it inside src/, or add a symlink to it from project's node_modules/.
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './components/App/App.js';
import registerServiceWorker from './registerServiceWorker';
import axios from 'axios'
// import mongoose from './server.js'
// import mongoose from '../db/connection.js'
var express = require("express");
// var mongoose= require("../db/connection.js");
ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();
var app = express();
var Post = mongoose.model("Post");
app.get("/api/posts", function(req, res){
Post.find({}).then(function(posts){
res.json(posts)
});
});
app.get("/api/posts/:name", function(req, res){
Post.findOne({name: req.params.name}).then(function(post){
res.json(post)
});
});
server.js
// ‘use strict’
var express = require(`express`);
// var mongoose = require(`mongoose`);
var bodyParser = require(`body-parser`);
var mongoose= require("../db/connection");
var app = express();
var router = express.Router();
var port = process.env.API_PORT || 3001;
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// router.get(‘/’, function(req, res) {
// res.json({ message: ‘API Initialized!’});
// });
// app.use(‘/api’, router);
app.listen(port, function() {
console.log(`api running on port ${port}`);
});
I would do as it recommends and move the db folder inside of src
. In place of data.js
[https://medium.com/@bryantheastronaut/react-getting-started-the-mern-stack-tutorial-feat-es6-de1a2886be50](from the MERN tutorial) you will have your db
folder.
have you changed the file paths after moving your folder around?
It had to do with create-react-app treating the express app as a react view.