如何在节点服务器上正确运行ajax?

时间:2019-07-10 11:40:41

标签: javascript node.js ajax express

我想在将新产品上载到数据库的表单上调用ajax函数。 即使我在script.js中禁用了事件的默认行为,该页面仍会由于router.post()方法而刷新。

我的index.js(后端):

router.post('/dashboard', (req, res) => {

    const{name, pricePerUnit, productDescription, productAmmount} = req.body;
    let errors = [];
    console.log(global.useremail);

    //Check required fields
    if(!name || !pricePerUnit || !productDescription || !productAmmount){
        errors.push({msg : "Enter all fields"});
    }

    if(errors.length > 0){
        res.render('dashboard', {
            name,
            pricePerUnit,
            productDescription,
            productAmmount,
            errors,
        });
    }else{
        //Add record
    }
});

我的script.js(前端):

$(document).ready(()=>{

$('#submitNewProduct').submit((e)=>{
    e.preventDefault();

    const data = getFormDataAsJSON($('newproduct-form'));

    $.ajax({
        type: 'post',
        url: '/dashboard',
        data: data,
        dataType: 'json'
    });
});

});

2 个答案:

答案 0 :(得分:0)

编辑:我认为如果您使用.on("click", ...)而不是.submit(...)可以解决您的问题

$('#submitNewProduct').on("click", (e) => {
    e.preventDefault();
    ...

您使用relative path的方式就像您始终在节点应用程序上一样,但不是因为前端应用程序是在客户端执行的。

您必须像这样调用整个服务器节点url

$.ajax({
    type: 'post',
    url: 'http://localhost:8080/dashboard',
    data: data,
    dataType: 'json'
});

在我的示例中,您的服务器在localhost端口的8080上运行

答案 1 :(得分:0)

如果您在前端使用ajax,则您的服务器必须以JSON返回响应。

每次提交表单时,

res.render 都会从服务器端呈现页面。  因此您必须使用 res.json()

if(errors.length > 0){
     res.json({status:"error",errors:errors});
}else{
    //Add record
     res.json({status:"success",record:record});
}
相关问题