Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
348 views
in Technique[技术] by (71.8m points)

ajax - Handlebars: Access has been denied to resolve the property "_id" because it is not an "own property" of its parent

I'm new to JS and Handlebars, and would really appreciate some help with a project I'm working on. I'm using AJAX to create a new category, and am trying to then fetch that category back from the server (currently, if I refresh, the new category disappears. I understand AJAX is asynchronous, and am trying to get a response from the server if possible). Currently, I'm getting the following error:

Handlebars: Access has been denied to resolve the property "_id" because it is not an "own property" of its parent.

From the reading I've done, I believe this is happening because Handlebars 4.6.0 and on forbids accessing prototype properties and methods of the context object by default. In order to address this, I installed @handlebars/allow-prototype-access package, but I'm not sure how to use it in my app.engine. Could someone please help? Here's my app.js:


const {globalVariables} = require('./config/configuration')

const express = require('express');
const mongoose = require('mongoose');
const path = require('path');
const hbs = require('express-handlebars');
const {mongoDbUrl, PORT} = require('./config/configuration');
const flash = require('connect-flash');
const session = require('express-session');
const {selectOption} = require('./config/customFunctions');
const fileUpload = require('express-fileUpload');
const methodOverride = require('method-override');
const {allowInsecurePrototypeAccess} = require('@handlebars/allow-prototype-access');

const app = express();

/* Configure Mongoose to Connect MongoDB */
mongoose.connect(mongoDbUrl, { useNewUrlParser: true })
    .then(response => {
        console.log("MongoDB Connected Successfully.", { useNewUrlParser: true });
    }) .catch(err => {
        console.log("Database connection failed", err)
    });



/* Configure express*/
app.use(express.json());
app.use(express.urlencoded({extended: true}))
app.use(express.static(path.join(__dirname, 'public')));

/*flash and session*/
app.use(session({
    secret: 'anysecret',
    saveUninitialized: true,
    resave: true
}))

app.use(flash());

app.use(globalVariables);

app.use(fileUpload({
    limits: { fileSize: 50 * 1024 * 1024 },
  }));

/* Setup View Engine To Use Handlebars */
app.engine('handlebars', hbs({defaultLayout: 'default', helpers: {select: selectOption}}));
app.set('view engine', 'handlebars');

/* Method Override Middleware */
app.use(methodOverride('newMethod'));


/* Routes */
const defaultRoutes = require('./routes/defaultRoutes');
const adminRoutes = require('./routes/adminRoutes');

app.use('/', defaultRoutes);
app.use('/admin', adminRoutes);

app.listen(PORT, () => {
    console.log(`Server is running on port 3000`);
})

Here is the .handlebars form I am using to create the category:

 $("#create-category-button").on('click', function (e) {
            e.preventDefault();

            var data = $("#category-title").val();

            $.ajax({
                url: '/admin/category',
                type: 'POST',
                data: {name: data},
                success: function (response) {

                    var html = `<tr>
                        <td>${response.title}</td>
                        <td class="d-flex justify-content-center">
                            <a href="/admin/category/edit/${response._id}" class="btn btn-sm btn-warning mr-2">Edit</a>
                            <form action="/admin/category/${response._id}?newMethod=DELETE" method="post">
                                <button class="btn btn-sm btn-danger" type="submit">Delete</button>
                            </form>
                        </td>
                    </tr>`;

                        console.log(response);
                    $(".category-list").append(html);

                }
            });

            $("#category-title").val('');
        });

Thank you so much in advance for your help!

question from:https://stackoverflow.com/questions/66051480/handlebars-access-has-been-denied-to-resolve-the-property-id-because-it-is-n

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Got it! I had to adjust me app.engine as below:

app.engine('handlebars', hbs( {defaultLayout: 'default', helpers: {select: selectOption}, handlebars: allowInsecurePrototypeAccess(_handlebars)}));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...