简体   繁体   English

JQuery POST 到 NODEJS(快递)

[英]JQuery POST to NODEJS (express)

EDIT: Project on Github: https://github.com/jackphumphrey/medisearch编辑:Github 上的项目: https://github.com/jackphumphrey/medisearch

I am very new to NODEjs so sorry if this is an easy/dumb question我对 NODEjs 很陌生,如果这是一个简单/愚蠢的问题,我很抱歉

I am attempting to send a POST request w/ JQuery ($.post) which is located: /public/javascripts/user.js我正在尝试使用 JQuery ($.post) 发送 POST 请求,该请求位于:/public/javascripts/user.js

user.js in called in the of index.html after jquery user.js 在 jquery 之后的 index.html 中调用

index.html loads fine, however the $.post request sends an error index.html 加载正常,但是 $.post 请求发送错误

I think my main problem is that I don't know WHERE (as in location in node) I am suppose to send the post request我认为我的主要问题是我不知道 WHERE(如节点中的位置)我想发送 post 请求

My directory: mainfolder/我的目录:主文件夹/

public/index.html & public/javascripts/user.js public/index.html & public/javascripts/user.js

app.js & routes/users.js, routes/index.js app.js & 路由/users.js、路由/index.js

user.js (located in public/) user.js(位于公共/)

 $.post('/users', JSON.stringify({username: 'data', useremail: 'data@data.com'}), function(response, status) { }, "json").done(function(response) { alert(response); }).fail(function(xhr, status, error) { alert('error: ' + error + ' status: ' + status); }).always(function(response) { console.log('^ RESPONSE: ' + response); });

users.js (located in routes/) users.js(位于 routes/)

 var express = require('express'); var router = express.Router(); router.post('/users', function(req, res) { var userName = req.body.username; var userEmail = req.body.useremail; console.log('Username: ' + userName + ' Email: ' + userEmail); res.send('Username: ' + userName + ' Email: ' + userEmail); }); module.exports = router;

I am running it on digital ocean @ port 8080我在数字海洋@端口 8080 上运行它

Use the jquery code below:使用下面的 jquery 代码:

$("button").click(function(){
      $.post("/users",
      {
        name: "osasere",
        city: "stack"
      },
      function(data, status){
        console.log("Data: " + data + "\nStatus: " + status);
      });
});

In your app.js file make sure to use:在您的 app.js 文件中确保使用:

const express = require('express')
const userRouter = require('./routes/users')
const app = express()

app.use(express.urlencoded({ extended: false }))

app.use(userRouter)

If it doesn't work, try to contact me.如果它不起作用,请尝试与我联系。

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

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