我在MEAN堆栈上处理HTTP请求。
当我在localhost上开发时,所有请求都有效。
但是,当我尝试通过制作执行相同的请求时,它们不起作用。
这是我在尝试发布时遇到的错误...
ERROR SyntaxError: Unexpected token < in JSON at position 0
at JSON.parse (<anonymous>)
发送POST请求后,我也收到了GET错误。
GET http://atozinsurance.herokuapp.com/post 503 (Service Unavailable)
我知道这意味着我接收的是HTML而不是JSON。我的代码在申请HTML时遇到了什么错误?
这是我发布的NodeJS路线
var express = require('express');
var router = express.Router();
var jwt = require('jsonwebtoken');
var Post = require('../models/post');
router.get('/', function(req, res, next) {
Post.find()
.exec(function(err, posts){
if (err) {
return res.status(500).json({
title: 'An error occurred',
error: err
});
}
res.status(200).json({
message: 'Success',
obj: posts
});
});
});
// router.use('/', function (req, res, next) {
// jwt.verify(req.query.token, 'secret', function (err, decoded) {
// if (err) {
// return res.status(401).json({
// title: 'Not Authenticated',
// error: err
// });
// }
// next();
// })
// });
router.post('/', function (req, res, next) {
const post = new Post({
title: req.body.title,
content: req.body.content,
date: req.body.date
});
post.save(function(err, result) {
if (err) {
return res.status(500).json({
title: 'An error occured',
error: err
});
}
res.status(201).json({
message: 'Post saved',
obj: result
});
});
});
router.patch('/:id', function (req, res, next) {
Post.findById(req.params.id, function (err, post) {
if (err) {
return res.status(500).json({
title: 'An error occurred',
error: err
});
}
if (!post) {
return res.status(500).json({
title: 'No Post Found!',
error: {message: 'Post not found'}
});
}
post.title = req.body.title;
post.content = req.body.content;
post.date = req.body.date;
post.save(function(err, result) {
if (err) {
return res.status(500).json({
title: 'An error occurred',
error: err
});
}
res.status(200).json({
message: 'Updated post',
obj: result
});
});
});
});
router.delete('/:id', function(req, res, next) {
Post.findById(req.params.id, function (err, post) {
if (err) {
return res.status(500).json({
title: 'An error occurred',
error: err
});
}
if (!post) {
return res.status(500).json({
title: 'No Post Found!',
error: {post: 'Post not found'}
});
}
post.remove(function(err, result) {
if (err) {
return res.status(500).json({
title: 'An error occurred',
error: err
});
}
res.status(200).json({
message: 'Deleted post',
obj: result
});
});
});
});
module.exports = router;
这是我通过Angular发送请求的服务。
import { Http, Response, Headers } from "@angular/http";
import { Injectable, EventEmitter } from "@angular/core";
import 'rxjs/Rx';
import { Observable } from "rxjs";
import { Post } from "./blog.model";
@Injectable()
export class PostService {
private posts: Post[] = [];
inputEditMessage = new EventEmitter<Post>();
url = 'http://atozinsurance.herokuapp.com/post';
devUrl = 'http://localhost:8080/post/';
constructor(private http: Http) {
}
addPost(post: Post) {
const body = JSON.stringify(post);
const headers = new Headers({'Content-Type': 'application/json'});
// const token = localStorage.getItem('token')
// ? '?token=' + localStorage.getItem('token')
// : '';
return this.http.post(this.url, body, {headers: headers})
.map((response: Response) => {
const result = response.json();
const post = new Post(
result.obj.title,
result.obj.content,
result.obj.date,
result.obj._id);
this.posts.push(post);
return post;
})
.catch((error: Response) => Observable.throw(error.json()));
}
getPosts() {
return this.http.get(this.url)
.map((response: Response) => {
const posts = response.json().obj;
let transformedPosts: Post[] = [];
for (let post of posts) {
transformedPosts.push(new Post(
post.title,
post.content,
post.date,
post._id)
);
}
this.posts = transformedPosts;
return transformedPosts;
})
.catch((error: Response) => Observable.throw(error.json()));
}
editPost(post: Post) {
this.inputEditMessage.emit(post);
}
updatePost(post: Post) {
const body = JSON.stringify(post);
const headers = new Headers({'Content-Type': 'application/json'});
const token = localStorage.getItem('token')
? '?token=' + localStorage.getItem('token')
: '';
return this.http.patch(this.url + '/' + post.postId + token, body, {headers: headers})
.map((response: Response) => response.json())
.catch((error: Response) => Observable.throw(error.json()));
}
deletePost(post: Post) {
this.posts.splice(this.posts.indexOf(post), 1);
const token = localStorage.getItem('token')
? '?token=' + localStorage.getItem('token')
: '';
return this.http.delete(this.url + '/' + post.postId + token)
.map((response: Response) => response.json())
.catch((error: Response) => Observable.throw(error.json()));
}
}
正如我之前所说,使用localhost(称为devUrl)它可以正常工作。但是当我切换到url或生产模式时,它会失败。
任何人都知道错误在哪里?
编辑***这是我收到的HTML错误。
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta charset="utf-8">
<title>Application Error</title>
<style media="screen">
html,body,iframe {
margin: 0;
padding: 0;
}
html,body {
height: 100%;
overflow: hidden;
}
iframe {
width: 100%;
height: 100%;
border: 0;
}
</style>
</head>
<body>
<iframe src="//www.herokucdn.com/error-pages/application-error.html"></iframe>
</body>
</html>
编辑***
这是我的server.js文件
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const bodyParser = require("body-parser");
const mongoose = require('mongoose');
const appRoutes = require('./routes/app');
const mailRoutes = require('./routes/mail');
const userRoutes = require('./routes/user');
const postRoutes = require('./routes/post');
const app = express();
const uristring =
process.env.MONGOLAB_URI ||
process.env.MONGOHQ_URL ||
'localhost:27017/atoz';
mongoose.connect(uristring, function (err, res) {
if (err) {
console.log ('ERROR connecting to: ' + uristring + '. ' + err);
} else {
console.log ('Succeeded connecting to: ' + uristring);
}
});
app.set('views', path.join(__dirname, './dist'));
app.set('view engine', 'ejs');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, './dist')));
app.use(function (req,res,next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers','Origin, X-Requested-With, Content-Type, Accept');
res.header('Access-Control-Allow-Methods', 'POST, GET, PATCH, DELETE, OPTIONS');
next();
});
app.use('/user', userRoutes);
app.use('/post', postRoutes);
app.use('/mail', mailRoutes);
app.use('/', appRoutes);
//catch 404 and forward error handler
app.use('*', appRoutes);
app.listen(process.env.PORT || 8080);
module.exports = app;
编辑*** 这是我从heroku日志收到的错误
at=error code=H12 desc="Request timeout" method=POST path="/post" host=atozinsurance.herokuapp.com request_id=c4e340d3-8ee3-4c2f-ae12-e56e7439c0f1 fwd="68.111.238.205" dyno=web.1 connect=1ms service=30001ms status=503 bytes=0 protocol=http
Macs-MacBook-Pro-2:atoz-app joncorrin$
答案 0 :(得分:0)
对于有此问题的任何人。您正在从Heroku接收HTML。 HTML中的第一个字符是&lt;这解释了为什么它绝对不是JSON。
我的解决方案: 我没有为MONGOLAB_URL设置我的环境变量。因此,heroku无法正确连接到数据库,请求超时。
将其设置为MongLab插件并完美运行。