Angular2 http post请求到另一个端口上的nodejs服务器
Posted
技术标签:
【中文标题】Angular2 http post请求到另一个端口上的nodejs服务器【英文标题】:Angular2 http post request to nodejs server on another port 【发布时间】:2017-09-07 10:59:36 【问题描述】:我有一个在 localhost:4200 上运行的 angular2 应用程序,一个 nodejs 服务器在 localhost:3000 上运行。 我想使用 http.post 将数据发布到服务器,但我在 req.body 或 req.params 的 nodejs 服务器中未定义。 起初,我从服务器渲染了 angular2 应用程序,这意味着我只有 localhost:3000 的 nodejs 并且我完全没有问题,所以这不是语法问题,但是当我想分离客户端和服务器,我无法发出任何发布请求。
GET 请求有效。
我有 TodoService 与服务器交互,并具有 saveTodo 功能。 newTodo 是有效的,并且 console.log 提供了正确的信息。 我尝试过发布 json 并使用 url-params 发布,但都不起作用: 发布json:
saveTodo(newTodo: any)
let headers = new Headers();
headers.append('Content-Type','application/json');
return this.http.post('/api/v1/todo', JSON.stringify(newTodo), headers: headers)
.map(res => res.json());
发布网址参数:
saveTodo(newTodo: any)
let headers = new Headers();
headers.append('Content-Type','application/x-www-form-urlencoded');
let body = new URLSearchParams();
body.set('newTodo', newTodo);
return this.http.post('/api/v1/todo', body, headers: headers)
.map(res => res.json());
我用这个从组件中调用函数:
addTodo(event: any)
let newTodo =
text: 'check',
isCompleted: false
;
this.todoService.saveTodo(newTodo).subscribe((x: Todo) =>
this.todos.push(x)
);
我对这两个选项都没有定义。 我也尝试过使用 FormData 发帖,但这也没有用。
起初我以为这是cors问题,所以经过一些研究我发现我需要用angular2定义代理,所以我创建了proxy.config.json文件:
"/api":
"target": "http://localhost:3000",
"secure": "false"
所以每次我说去路由/api,我的意思是http://localhost:3000
,nodejs服务器。
我也尝试使用 ionic2 以相同的方式发布请求,但遇到了同样的问题。 在 ionic2 中,我将以下内容添加到 ionic.config.json 文件中:
"proxies" :[
"path" :"/api",
"proxyUrl" : "http://localhost:3000/api"
这是我的 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 cors = require('cors');
var index = require('./routes/index');
var users = require('./routes/users');
var app = express();
// Get our API routes
const api = require('./routes/api');
var todos = require ('./routes/todos');
app.use(cors());
// Set our api routes
app.use('/api', api);
app.use('/api/v1/',todos);
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// 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(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
app.use('/users', users);
// 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;
如您所见,我还使用了来自 npm 的 cors 包和 app.use(cors());
这是路线:
router.post('/todo',function (req,res,next)
var todo = req.body;
if(!todo.text || !(todo.isCompleted + ''))
res.status(400);
res.json(
"error": "Invalid Data"
);
else
db.todos.save(todo,function (err,result)
if(err)
res.send(err);
else
res.json(result);
)
);
请帮帮我,谢谢。
编辑: 这是@jaaaaaay 想要的记录请求:
IncomingMessage
_readableState:
ReadableState
objectMode: false,
highWaterMark: 16384,
buffer: BufferList head: null, tail: null, length: 0 ,
length: 0,
pipes: null,
pipesCount: 0,
flowing: null,
ended: false,
endEmitted: false,
reading: false,
sync: true,
needReadable: false,
emittedReadable: false,
readableListening: false,
resumeScheduled: false,
defaultEncoding: 'utf8',
ranOut: false,
awaitDrain: 0,
readingMore: true,
decoder: null,
encoding: null ,
readable: true,
domain: null,
_events: ,
_eventsCount: 0,
_maxListeners: undefined,
socket:
Socket
connecting: false,
_hadError: false,
_handle:
TCP
bytesRead: 626,
_externalStream: ,
fd: -1,
reading: true,
owner: [Circular],
onread: [Function: onread],
onconnection: null,
writeQueueSize: 0 ,
_parent: null,
_host: null,
_readableState:
ReadableState
objectMode: false,
highWaterMark: 16384,
buffer: [Object],
length: 0,
pipes: null,
pipesCount: 0,
flowing: true,
ended: false,
endEmitted: false,
reading: true,
sync: false,
needReadable: true,
emittedReadable: false,
readableListening: false,
resumeScheduled: false,
defaultEncoding: 'utf8',
ranOut: false,
awaitDrain: 0,
readingMore: false,
decoder: null,
encoding: null ,
readable: true,
domain: null,
_events:
end: [Object],
finish: [Function: onSocketFinish],
_socketEnd: [Function: onSocketEnd],
drain: [Object],
timeout: [Function],
error: [Function: socketOnError],
close: [Object],
data: [Function: socketOnData],
resume: [Function: onSocketResume],
pause: [Function: onSocketPause] ,
_eventsCount: 10,
_maxListeners: undefined,
_writableState:
WritableState
objectMode: false,
highWaterMark: 16384,
needDrain: false,
ending: false,
ended: false,
finished: false,
decodeStrings: false,
defaultEncoding: 'utf8',
length: 0,
writing: false,
corked: 0,
sync: true,
bufferProcessing: false,
onwrite: [Function],
writecb: null,
writelen: 0,
bufferedRequest: null,
lastBufferedRequest: null,
pendingcb: 0,
prefinished: false,
errorEmitted: false,
bufferedRequestCount: 0,
corkedRequestsFree: [Object] ,
writable: true,
allowHalfOpen: true,
destroyed: false,
_bytesDispatched: 0,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server:
Server
domain: null,
_events: [Object],
_eventsCount: 4,
_maxListeners: undefined,
_connections: 1,
_handle: [Object],
_usingSlaves: false,
_slaves: [],
_unref: false,
allowHalfOpen: true,
pauseOnConnect: false,
httpAllowHalfOpen: false,
timeout: 120000,
_pendingResponseData: 0,
_connectionKey: '6::::3000' ,
_server:
Server
domain: null,
_events: [Object],
_eventsCount: 4,
_maxListeners: undefined,
_connections: 1,
_handle: [Object],
_usingSlaves: false,
_slaves: [],
_unref: false,
allowHalfOpen: true,
pauseOnConnect: false,
httpAllowHalfOpen: false,
timeout: 120000,
_pendingResponseData: 0,
_connectionKey: '6::::3000' ,
_idleTimeout: 120000,
_idleNext:
TimersList
_idleNext: [Circular],
_idlePrev: [Circular],
_timer: [Object],
_unrefed: true,
msecs: 120000 ,
_idlePrev:
TimersList
_idleNext: [Circular],
_idlePrev: [Circular],
_timer: [Object],
_unrefed: true,
msecs: 120000 ,
_idleStart: 2718,
parser:
HTTPParser
'0': [Function: parserOnHeaders],
'1': [Function: parserOnHeadersComplete],
'2': [Function: parserOnBody],
'3': [Function: parserOnMessageComplete],
'4': [Function: onParserExecute],
_headers: [],
_url: '',
_consumed: true,
socket: [Circular],
incoming: [Circular],
outgoing: null,
maxHeaderPairs: 2000,
onIncoming: [Function: parserOnIncoming] ,
on: [Function: socketOnWrap],
_paused: false,
read: [Function],
_consuming: true,
_httpMessage:
ServerResponse
domain: null,
_events: [Object],
_eventsCount: 1,
_maxListeners: undefined,
output: [],
outputEncodings: [],
outputCallbacks: [],
outputSize: 0,
writable: true,
_last: false,
upgrading: false,
chunkedEncoding: false,
shouldKeepAlive: true,
useChunkedEncodingByDefault: true,
sendDate: true,
_removedHeader: ,
_contentLength: null,
_hasBody: true,
_trailer: '',
finished: false,
_headerSent: false,
socket: [Circular],
connection: [Circular],
_header: null,
_headers: [Object],
_headerNames: [Object],
_onPendingData: [Function: updateOutgoingData],
req: [Circular],
locals: ,
connection:
Socket
connecting: false,
_hadError: false,
_handle:
TCP
bytesRead: 626,
_externalStream: ,
fd: -1,
reading: true,
owner: [Circular],
onread: [Function: onread],
onconnection: null,
writeQueueSize: 0 ,
_parent: null,
_host: null,
_readableState:
ReadableState
objectMode: false,
highWaterMark: 16384,
buffer: [Object],
length: 0,
pipes: null,
pipesCount: 0,
flowing: true,
ended: false,
endEmitted: false,
reading: true,
sync: false,
needReadable: true,
emittedReadable: false,
readableListening: false,
resumeScheduled: false,
defaultEncoding: 'utf8',
ranOut: false,
awaitDrain: 0,
readingMore: false,
decoder: null,
encoding: null ,
readable: true,
domain: null,
_events:
end: [Object],
finish: [Function: onSocketFinish],
_socketEnd: [Function: onSocketEnd],
drain: [Object],
timeout: [Function],
error: [Function: socketOnError],
close: [Object],
data: [Function: socketOnData],
resume: [Function: onSocketResume],
pause: [Function: onSocketPause] ,
_eventsCount: 10,
_maxListeners: undefined,
_writableState:
WritableState
objectMode: false,
highWaterMark: 16384,
needDrain: false,
ending: false,
ended: false,
finished: false,
decodeStrings: false,
defaultEncoding: 'utf8',
length: 0,
writing: false,
corked: 0,
sync: true,
bufferProcessing: false,
onwrite: [Function],
writecb: null,
writelen: 0,
bufferedRequest: null,
lastBufferedRequest: null,
pendingcb: 0,
prefinished: false,
errorEmitted: false,
bufferedRequestCount: 0,
corkedRequestsFree: [Object] ,
writable: true,
allowHalfOpen: true,
destroyed: false,
_bytesDispatched: 0,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server:
Server
domain: null,
_events: [Object],
_eventsCount: 4,
_maxListeners: undefined,
_connections: 1,
_handle: [Object],
_usingSlaves: false,
_slaves: [],
_unref: false,
allowHalfOpen: true,
pauseOnConnect: false,
httpAllowHalfOpen: false,
timeout: 120000,
_pendingResponseData: 0,
_connectionKey: '6::::3000' ,
_server:
Server
domain: null,
_events: [Object],
_eventsCount: 4,
_maxListeners: undefined,
_connections: 1,
_handle: [Object],
_usingSlaves: false,
_slaves: [],
_unref: false,
allowHalfOpen: true,
pauseOnConnect: false,
httpAllowHalfOpen: false,
timeout: 120000,
_pendingResponseData: 0,
_connectionKey: '6::::3000' ,
_idleTimeout: 120000,
_idleNext:
TimersList
_idleNext: [Circular],
_idlePrev: [Circular],
_timer: [Object],
_unrefed: true,
msecs: 120000 ,
_idlePrev:
TimersList
_idleNext: [Circular],
_idlePrev: [Circular],
_timer: [Object],
_unrefed: true,
msecs: 120000 ,
_idleStart: 2718,
parser:
HTTPParser
'0': [Function: parserOnHeaders],
'1': [Function: parserOnHeadersComplete],
'2': [Function: parserOnBody],
'3': [Function: parserOnMessageComplete],
'4': [Function: onParserExecute],
_headers: [],
_url: '',
_consumed: true,
socket: [Circular],
incoming: [Circular],
outgoing: null,
maxHeaderPairs: 2000,
onIncoming: [Function: parserOnIncoming] ,
on: [Function: socketOnWrap],
_paused: false,
read: [Function],
_consuming: true,
_httpMessage:
ServerResponse
domain: null,
_events: [Object],
_eventsCount: 1,
_maxListeners: undefined,
output: [],
outputEncodings: [],
outputCallbacks: [],
outputSize: 0,
writable: true,
_last: false,
upgrading: false,
chunkedEncoding: false,
shouldKeepAlive: true,
useChunkedEncodingByDefault: true,
sendDate: true,
_removedHeader: ,
_contentLength: null,
_hasBody: true,
_trailer: '',
finished: false,
_headerSent: false,
socket: [Circular],
connection: [Circular],
_header: null,
_headers: [Object],
_headerNames: [Object],
_onPendingData: [Function: updateOutgoingData],
req: [Circular],
locals: ,
httpVersionMajor: 1,
httpVersionMinor: 1,
httpVersion: '1.1',
complete: false,
headers:
connection: 'keep-alive',
'content-length': '29',
pragma: 'no-cache',
'cache-control': 'no-cache',
accept: 'application/json, text/plain, */*',
origin: 'http://localhost:8100',
'user-agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (Khtml, like Gecko) Chrome/57.0.2987.133 Safari/537.36',
'content-type': 'application/x-www-form-urlencoded',
referer: 'http://localhost:8100/',
'accept-encoding': 'gzip, deflate, br',
'accept-language': 'he-IL,he;q=0.8,en-US;q=0.6,en;q=0.4',
cookie: 'Webstorm-b127fad0=32f013a9-8b83-4566-a999-5f35bf7360c8; io=uJyvB9XFivORLmROAAAC',
host: 'localhost:3000' ,
rawHeaders:
[ 'connection',
'keep-alive',
'content-length',
'29',
'pragma',
'no-cache',
'cache-control',
'no-cache',
'accept',
'application/json, text/plain, */*',
'origin',
'http://localhost:8100',
'user-agent',
'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36',
'content-type',
'application/x-www-form-urlencoded',
'referer',
'http://localhost:8100/',
'accept-encoding',
'gzip, deflate, br',
'accept-language',
'he-IL,he;q=0.8,en-US;q=0.6,en;q=0.4',
'cookie',
'Webstorm-b127fad0=32f013a9-8b83-4566-a999-5f35bf7360c8; io=uJyvB9XFivORLmROAAAC',
'Host',
'localhost:3000' ],
trailers: ,
rawTrailers: [],
upgrade: false,
url: '/todo',
method: 'POST',
statusCode: null,
statusMessage: null,
client:
Socket
connecting: false,
_hadError: false,
_handle:
TCP
bytesRead: 626,
_externalStream: ,
fd: -1,
reading: true,
owner: [Circular],
onread: [Function: onread],
onconnection: null,
writeQueueSize: 0 ,
_parent: null,
_host: null,
_readableState:
ReadableState
objectMode: false,
highWaterMark: 16384,
buffer: [Object],
length: 0,
pipes: null,
pipesCount: 0,
flowing: true,
ended: false,
endEmitted: false,
reading: true,
sync: false,
needReadable: true,
emittedReadable: false,
readableListening: false,
resumeScheduled: false,
defaultEncoding: 'utf8',
ranOut: false,
awaitDrain: 0,
readingMore: false,
decoder: null,
encoding: null ,
readable: true,
domain: null,
_events:
end: [Object],
finish: [Function: onSocketFinish],
_socketEnd: [Function: onSocketEnd],
drain: [Object],
timeout: [Function],
error: [Function: socketOnError],
close: [Object],
data: [Function: socketOnData],
resume: [Function: onSocketResume],
pause: [Function: onSocketPause] ,
_eventsCount: 10,
_maxListeners: undefined,
_writableState:
WritableState
objectMode: false,
highWaterMark: 16384,
needDrain: false,
ending: false,
ended: false,
finished: false,
decodeStrings: false,
defaultEncoding: 'utf8',
length: 0,
writing: false,
corked: 0,
sync: true,
bufferProcessing: false,
onwrite: [Function],
writecb: null,
writelen: 0,
bufferedRequest: null,
lastBufferedRequest: null,
pendingcb: 0,
prefinished: false,
errorEmitted: false,
bufferedRequestCount: 0,
corkedRequestsFree: [Object] ,
writable: true,
allowHalfOpen: true,
destroyed: false,
_bytesDispatched: 0,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server:
Server
domain: null,
_events: [Object],
_eventsCount: 4,
_maxListeners: undefined,
_connections: 1,
_handle: [Object],
_usingSlaves: false,
_slaves: [],
_unref: false,
allowHalfOpen: true,
pauseOnConnect: false,
httpAllowHalfOpen: false,
timeout: 120000,
_pendingResponseData: 0,
_connectionKey: '6::::3000' ,
_server:
Server
domain: null,
_events: [Object],
_eventsCount: 4,
_maxListeners: undefined,
_connections: 1,
_handle: [Object],
_usingSlaves: false,
_slaves: [],
_unref: false,
allowHalfOpen: true,
pauseOnConnect: false,
httpAllowHalfOpen: false,
timeout: 120000,
_pendingResponseData: 0,
_connectionKey: '6::::3000' ,
_idleTimeout: 120000,
_idleNext:
TimersList
_idleNext: [Circular],
_idlePrev: [Circular],
_timer: [Object],
_unrefed: true,
msecs: 120000 ,
_idlePrev:
TimersList
_idleNext: [Circular],
_idlePrev: [Circular],
_timer: [Object],
_unrefed: true,
msecs: 120000 ,
_idleStart: 2718,
parser:
HTTPParser
'0': [Function: parserOnHeaders],
'1': [Function: parserOnHeadersComplete],
'2': [Function: parserOnBody],
'3': [Function: parserOnMessageComplete],
'4': [Function: onParserExecute],
_headers: [],
_url: '',
_consumed: true,
socket: [Circular],
incoming: [Circular],
outgoing: null,
maxHeaderPairs: 2000,
onIncoming: [Function: parserOnIncoming] ,
on: [Function: socketOnWrap],
_paused: false,
read: [Function],
_consuming: true,
_httpMessage:
ServerResponse
domain: null,
_events: [Object],
_eventsCount: 1,
_maxListeners: undefined,
output: [],
outputEncodings: [],
outputCallbacks: [],
outputSize: 0,
writable: true,
_last: false,
upgrading: false,
chunkedEncoding: false,
shouldKeepAlive: true,
useChunkedEncodingByDefault: true,
sendDate: true,
_removedHeader: ,
_contentLength: null,
_hasBody: true,
_trailer: '',
finished: false,
_headerSent: false,
socket: [Circular],
connection: [Circular],
_header: null,
_headers: [Object],
_headerNames: [Object],
_onPendingData: [Function: updateOutgoingData],
req: [Circular],
locals: ,
_consuming: false,
_dumped: false,
next: [Function: next],
baseUrl: '/api/v1',
originalUrl: '/api/v1/todo',
_parsedUrl:
Url
protocol: null,
slashes: null,
auth: null,
host: null,
port: null,
hostname: null,
hash: null,
search: null,
query: null,
pathname: '/todo',
path: '/todo',
href: '/todo',
_raw: '/todo' ,
params: ,
query: ,
res:
ServerResponse
domain: null,
_events: finish: [Function: resOnFinish] ,
_eventsCount: 1,
_maxListeners: undefined,
output: [],
outputEncodings: [],
outputCallbacks: [],
outputSize: 0,
writable: true,
_last: false,
upgrading: false,
chunkedEncoding: false,
shouldKeepAlive: true,
useChunkedEncodingByDefault: true,
sendDate: true,
_removedHeader: ,
_contentLength: null,
_hasBody: true,
_trailer: '',
finished: false,
_headerSent: false,
socket:
Socket
connecting: false,
_hadError: false,
_handle: [Object],
_parent: null,
_host: null,
_readableState: [Object],
readable: true,
domain: null,
_events: [Object],
_eventsCount: 10,
_maxListeners: undefined,
_writableState: [Object],
writable: true,
allowHalfOpen: true,
destroyed: false,
_bytesDispatched: 0,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: [Object],
_server: [Object],
_idleTimeout: 120000,
_idleNext: [Object],
_idlePrev: [Object],
_idleStart: 2718,
parser: [Object],
on: [Function: socketOnWrap],
_paused: false,
read: [Function],
_consuming: true,
_httpMessage: [Circular] ,
connection:
Socket
connecting: false,
_hadError: false,
_handle: [Object],
_parent: null,
_host: null,
_readableState: [Object],
readable: true,
domain: null,
_events: [Object],
_eventsCount: 10,
_maxListeners: undefined,
_writableState: [Object],
writable: true,
allowHalfOpen: true,
destroyed: false,
_bytesDispatched: 0,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: [Object],
_server: [Object],
_idleTimeout: 120000,
_idleNext: [Object],
_idlePrev: [Object],
_idleStart: 2718,
parser: [Object],
on: [Function: socketOnWrap],
_paused: false,
read: [Function],
_consuming: true,
_httpMessage: [Circular] ,
_header: null,
_headers:
'x-powered-by': 'Express',
'access-control-allow-origin': '*' ,
_headerNames:
'x-powered-by': 'X-Powered-By',
'access-control-allow-origin': 'Access-Control-Allow-Origin' ,
_onPendingData: [Function: updateOutgoingData],
req: [Circular],
locals: ,
route: Route path: '/todo', stack: [ [Object] ], methods: post: true
【问题讨论】:
在你定义“todo”之后,你能不能在 nodejs 服务器中 console.log(req) 并告诉我们请求中有什么? @Jaaaaaaay 我为你编辑了这篇文章。 【参考方案1】:嗯,我找到了答案,我不敢相信这太容易了...... 浪费了 3 天来解决它,但后来我找到了这个:
我在 before 之前使用 body-parser 包定义了路由,这就是我未定义的原因。
Nodejs returns undefined for Angular 2 request
【讨论】:
以上是关于Angular2 http post请求到另一个端口上的nodejs服务器的主要内容,如果未能解决你的问题,请参考以下文章
从Angular2应用程序发送http post请求时如何启用CORS
如何使用 Angular2 向外部 API 发出 POST 请求?
Angular 2 http post 作为空对象或在关键端发送