node.js - node express 中ajax post請求參數接收不到?
問題描述
app.js
// bodyParser :ajax 請求的配置項//parseapplication/x-www-form-urlencodedapp.use(bodyParser.urlencoded({extended: false}));//parseapplication/json:接受 json 或者可以轉換為json的數據格式app.use(bodyParser.json({type: ’application/*+json’}));// 路由routes(app);
user.js
'use strict';var express = require(’express’);var router = express.Router();// 該路由使用的中間件 timeLogrouter.use(function timeLog(req, res, next) { console.log(’Time: ’, Date.now()); next();});// 定義網站主頁的路由router.get(’/’, function (req, res) { // console.log(req); res.send(’user home page’);});// 定義 about 頁面的路由router.get(’/about’, function (req, res) { console.log(req.query); res.send(’About user’);});// 定義 login 頁面的路由router.post(’/login’, function (req, res) { console.log(req); //**拿不到對應的ajax參數** res.send(’user login’);});// 定義 logout 頁面的路由router.post(’/logout’, function (req, res) { res.send(’user logout’);});module.exports = router;
page.js
$.ajax({ url: 'http://127.0.0.1:3000/user/login', type: 'post', data: {type: 'post',target: 'login' }, callback: function (data) {console.log(data); }})//data 信息Object {xhr: XMLHttpRequest, errorType: 'parsererror', error: SyntaxError: Unexpected token u in JSON at position 0 at Function.parse [as parseJSON] (<anonymo…}error:SyntaxError: Unexpected token u in JSON at position 0 at Function.parse [as parseJSON] (<anonymous>) at XMLHttpRequest.xhr.onreadystatechange (http://127.0.0.1:3000/src/common/zepto.js:1486:103)errorType:'parsererror'xhr:XMLHttpRequest__proto__:Object
問題:login的post請求中獲取不到相應的入參。
// 定義 login 頁面的路由router.post(’/login’, function (req, res) { console.log(req); //**拿不到對應的ajax參數** res.send(’user login’);});
備注:我先不打算做數據庫那一塊,先把基本的業務邏輯寫一些,下周才打算連接到數據庫相關的知識 。
同時我是前端開發,所以喜歡前后端分離,而不喜歡在服務端寫頁面模板,謝謝!
問題解答
回答1:// 定義 login 頁面的路由
router.post(’/login’, function (req, res) { console.log(req); //**拿不到對應的ajax參數** res.send(’user login’);});
req是undefined?還是req.body是undefined?
app.js文件中有沒有設置 app.use(’/user’, user);?
我是這樣做的,你參考一下。你的出現問題,可能是哪里設置不正確。
前端
$.ajax({ type: ’POST’, url: ’/post.html’, data, success: (data, status, xhr) => { console.log(data); }});
后端
let data = req.body;回答2:
router.post(’/user/login’, function (req, res) { console.log(req); //**拿不到對應的ajax參數** res.send(’user login’);});
或者
app.use(’/user’,require(’./user’));回答3:
errorType: 'parsererror'
你返回的不是一個 JSON
回答4:$.ajax({url: 'http://127.0.0.1:3000/user/login',type: 'post',contentType:’application/json’,data: JSON.stringify({ type: 'post', target: 'login'}),success: function (data) { console.log(data);} }) // 如果是用jquery的話 應該這么寫
相關文章:
1. python - 我在使用pip install -r requirements.txt下載時,為什么部分能下載,部分不能下載2. mysql - 分庫分表、分區、讀寫分離 這些都是用在什么場景下 ,會帶來哪些效率或者其他方面的好處3. node.js - nodejs開發中常用的連接mysql的庫4. 網頁爬蟲 - python 爬取網站 并解析非json內容5. mysql - jdbc的問題6. python - 編碼問題求助7. 視頻文件不能播放,怎么辦?8. windows7 ping不通虛擬機VMware上的linux(ubuntu)的ip9. python - 數據與循環次數對應不上10. mysql - 如何減少使用或者不用LEFT JOIN查詢?
