简体   繁体   English

Node.js AJAX删除403禁止

[英]Node.js AJAX Delete 403 Forbidden

I try to create way to delete images from server. 我尝试创建一种从服务器删除图像的方法。 For now i just want to handle DELETE request and show on console filePath... Server don't handle my request and send: 现在,我只想处理DELETE请求并在控制台filePath上显示...服务器不处理我的请求并发送:

jquery.min.js:4 DELETE http://localhost:3000/api/imagesbg/wedding-stock-2.jpg 403 (Forbidden) jquery.min.js:4删除http:// localhost:3000 / api / imagesbg / wedding-stock-2.jpg 403(禁止)

What i'm doing wrong? 我做错了什么?

Front(handlebars.js) 前(handlebars.js)

{{#each images}}
  <div class="row">
    {{#each this}}
        <div class="col-sm-4">
            <img src="/images/background-slider/{{this}}" class="img-responsive img-thumbnail" alt="{{this}}">
            <button type="button" class="btn btn-danger pull-right imgBgDel" file-name="{{this}}" >
                Delete
            </button>
        </div>
   {{/each}}
  </div></br>
{{/each}}

Script 脚本

$(function(){
  $('.delete-msg').hide();
  var url;
  $(".imgBgDel").on("click", function(){
      var url = 'http://localhost:3000/api/imagesbg/' + $(this).attr('file-name');
      var allObj = $(this).parent();

      $.ajax({
        url: url,
        type: 'DELETE',
        success: function(result) {
            allObj.remove();
            $('.delete-msg').slideToggle();
            setTimeout(function() {$('.delete-msg').slideToggle();}, 3000);
        },
        error: function(status, xhr) {
            console.log(status);
            alert("An error occured: " + xhr.status + " " + xhr.statusText + " + " + status);
        }
     });
  });
});

index.js index.js

router.delete('/api/imagesbg/:id', isAdmin, function(req, res, next){
  var filePath = '/images/background-slider/' + req.params.id;
  console.log(filePath);
}); //isAdmin check if logged user is admin

full app.js 完整的app.js

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var expressHbs = require('express-handlebars');
var mongoose = require('mongoose');
var session = require('express-session');
var passport = require('passport');
var flash = require('connect-flash');
var fs = require('fs');

var validator = require('express-validator');

var MongoStore = require('connect-mongo')(session);


var index = require('./routes/index');
var userRoutes = require('./routes/user');
var adminRoutes = require('./routes/admin');


var app = express();
var options = {
  user: 'xxx',
  pass: 'xxx'
};

mongoose.connect('mongodb://xxx', options);

require('./config/passport');

// view engine setup
app.engine('.hbs', expressHbs({defaultLayout: 'layout', extname: '.hbs'}) );
app.set('view engine', '.hbs');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(validator());
app.use(cookieParser());
app.use(session({
  secret: 'xxx',
  resave: false,
  saveUninitialized: false,
  store: new MongoStore({
    mongooseConnection: mongoose.connection
  }),
  cookie: {
    maxAge: 180 * 60 * 1000 //how long session lives 180 minutes
  }
}));
app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(path.join(__dirname, 'public')));

//bootstrap and jquery
app.use('/js', express.static(__dirname + '/node_modules/bootstrap/dist/js')); // redirect bootstrap JS
app.use('/js', express.static(__dirname + '/node_modules/jquery/dist')); // redirect JS jQuery
app.use('/css', express.static(__dirname + '/node_modules/bootstrap/dist/css')); // redirect CSS bootstrap


app.use(function(req, res, next){
    res.locals.login = req.isAuthenticated();
    res.locals.adminLogin = (req.isAuthenticated()&&req.user.admin);
    res.locals.session = req.session;
    next();
});


app.use('/admin', adminRoutes);
app.use('/user', userRoutes);
app.use('/', index);


// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

and full index.js 和完整的index.js

var express = require('express');
var router = express.Router();
var BlogPost = require('../models/blogPost');
var csrf = require('csurf');
var passport = require('passport');
var fs = require('fs');




var csrfProtection = csrf();
router.use(csrfProtection);

router.get('/landing-edit', isAdmin, function(req, res, next){
var messages = req.flash('error');
fs.readdir('public/images/background-slider', function(err, files){
        if(err){
            console.log(err);
        }
        var arrTmp = [];
        var images = [];
        for(var i in files){
            if(arrTmp.length == 3){
                images.push(arrTmp);
                arrTmp = [];
            }
            arrTmp.push(files[i]);
        }
        if(arrTmp)
            images.push(arrTmp);
        console.log(images);

        res.render('admin/landing-bg-admin', {messages: messages, hasErrors: messages.length>0, images: images});
    });


});

router.delete('/api/imagesbg/:id', isAdmin, function(req, res, next){
    var filePath = '/images/background-slider/' + req.params.id;
    console.log(filePath);
    ///res.send(filePath);
});





module.exports = router;

function isAdmin(req, res, next){
    if(req.isAuthenticated() && req.user.admin){
        return next();
    }
    res.redirect('/');
}

I've had something very similar to this before. 我以前有过类似的东西。 The root cause is usually that when sending an XHR request like you're doing with $.ajax , the request doesn't include credentials by default . 根本原因通常是,当像发送$.ajax一样发送XHR请求时,默认情况下该请求不包含凭据 Since you're using passport for authentication, when the request goes to your server without the credentials, passport is stopping it and returning a 403 before it gets to your delete route handler. 由于您使用通行证进行身份验证,因此当请求在没有凭据的情况下发送到服务器时,通行证会停止该请求并返回403,然后再将其发送到删除路由处理程序。

I haven't solved this problem for $.ajax specifically, I used the fetch API, but trying adding: 我还没有为$.ajax解决这个问题,我使用了fetch API,但是尝试添加:

xhrFields: {
     withCredentials: true
}

to your $.ajax call. 到您的$.ajax电话。 If that doesn't work, try adding: 如果这样不起作用,请尝试添加:

username: "yourname"
password: "yourpass"

I'll bet that the root cause is that your request isn't sending your credentials. 我敢打赌,根本原因是您的请求没有发送您的凭据。

I don't know if your server uses CORS. 我不知道您的服务器是否使用CORS。 See https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS . 请参阅https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS Check Simple Requests title on the page. 在页面上检查“ 简单请求”标题。

If your server is using CORS, it won't allow you to do DELETE request as seen from other answer passport may not be the issue. 如果您的服务器使用的是CORS,则不允许您执行DELETE请求,因为从其他答案护照上看可能不是问题。 What I would suggest you doing is that try to change that ajax DELETE request to a POST request and move from there. 我建议您做的是尝试将ajax DELETE请求更改为POST请求,然后从那里移动。

use type: 'POST' , and you will still be able to remove the image, use the right functions with POST and 403: Forbidden will probably not occur. 使用type: 'POST' ,您仍然可以删除该图像,并在POST403: Forbidden使用正确的功能403: Forbidden可能不会发生被403: Forbidden

 router.get('/api/imagesbg/:id', isAdmin, (req, res, next)=>{ const query = {_id: req.params.id} if(!ObjectID.isValid(req.params.id)){ return res.render('error', {message: "Error didn't found the given id"}); } Blogpost.findOneAndRemove({ _id: query, _creator: req.user._id // if you have creator id else remove it }).then((post)=>{ if(!post){ return res.status(400).send(); } res.redirect('/home'); }).catch((e)=>{ res.status(400).send(); }); }); 

Try this and remove ajax code in your script file and try to GET the request and then delete the data. 尝试此操作,并删除脚本文件中的ajax代码,然后尝试获取请求,然后删除数据。

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

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