服务端
var http = require('http');
var express = require('express');
var bodyParser = require('body-parser');
var Crud = require('./crud.js');
var app = express();
// app.use(bodyParser.json);
app.use(bodyParser.urlencoded({
extended: true
}));
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods","POST,GET,OPTIONS");
res.header("Access-Control-Allow-Headers","Content-Type");
res.header("Content-Type", "application/json");
next();
});
只要已加上那行注释掉的 app.use(bodyParser.json)
浏览器请求就发不出去了
【更新】已将 app.use(bodyParser.json)
改为 app.use(bodyParser.json())
,改后可以发出去了,开始报400,node端报 SyntaxError: Unexpected token i
...
浏览器报文是这样的:
General
Request URL:……
Request Method:POST
Status Code:400 Bad Request
Remote Address:[::1]:3000
Referrer Policy:no-referrer-when-downgrade
Response Headers
Connection:keep-alive
Content-Length:1148
Content-Security-Policy:default-src 'self'
Content-Type:text/html; charset=utf-8
Date:Wed, 05 Jul 2017 04:17:59 GMT
X-Content-Type-Options:nosniff
X-Powered-By:Express
Request Headers
Accept:*/*
Accept-Encoding:gzip, deflate, br
Accept-Language:zh-CN,zh;q=0.8,zh-TW;q=0.6,en;q=0.4
Connection:keep-alive
Content-Length:18
Content-Type:application/json; charset=UTF-8
Host:localhost:3000
Origin:http://localhost:8082
Referer:http://localhost:8082/
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36
(排除跨域请求问题,跨域请求问题已用"Access-Control-"系列解决)
客户端代码这样的:
$.ajax({
url:……,
type:'post',
contentType:"application/json; charset=utf-8",
data:……,
success:function(res){
……
}
})
express版本4.0以上
是这样写的..