使用XMLHttpRequest在Javascript中发布错误
我正在从事一个需要API的项目,更确切地说,需要POST方法。我在上面读过一个堆栈溢出的线程,但没有多大帮助:他们只是说使用访问控制Allow Origin,尽管我已经这么做了。使用XMLHttpRequest在Javascript中发布错误,javascript,node.js,api,Javascript,Node.js,Api,我正在从事一个需要API的项目,更确切地说,需要POST方法。我在上面读过一个堆栈溢出的线程,但没有多大帮助:他们只是说使用访问控制Allow Origin,尽管我已经这么做了。 这里是前端的一面: const CHEMIN_AU_SERVEUR = "http://localhost:3000/api/stuff"; const func_that_post_the_card_created = (path, json) => { const request
这里是前端的一面:
const CHEMIN_AU_SERVEUR = "http://localhost:3000/api/stuff";
const func_that_post_the_card_created = (path, json) => {
const request_projets_post = new XMLHttpRequest();
request_projets_post.open("POST", path, true);
request_projets_post.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request_projets_post.send(JSON.stringify(json));
};
func_that_post_the_card_created(CHEMIN_AU_SERVEUR, "title=title&description=description&imageUrl=imageUrl&href=href&github_href=github_href");
这里是服务器端server.js
const http = require('http');
const app = require('./app');
app.set('port', process.env.PORT || 3000);
console.log(process.env.PORT || 3000);
const server = http.createServer(app);
server.listen(process.env.PORT || 3000);
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const ProjectScheme = require("./models/Project");
const mongoose = require("mongoose");
// The mongoose connect that will not show
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content, Accept, Content-Type, Authorization");
res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, PATCH, OPTIONS");
next();
});
app.use(bodyParser.json());
app.post("/api/stuff", (req, res, next) => {
const projet = new ProjectScheme({ ...req.body });
projet.save()
.then(() => res.status(201).json({ message: "Projet enregistré !" }))
.catch((error) => res.status(400).json({ error }));
});
const mongoose = require("mongoose");
const ProjectScheme = mongoose.Schema({
title: { type:String, required:true },
description: { type:String, required:true },
imageUrl: { type:String, required:true },
href: { type:String, required:true },
github_href: { type:String, required:true },
});
module.exports = mongoose.model('Projet', ProjectScheme);
app.js
const http = require('http');
const app = require('./app');
app.set('port', process.env.PORT || 3000);
console.log(process.env.PORT || 3000);
const server = http.createServer(app);
server.listen(process.env.PORT || 3000);
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const ProjectScheme = require("./models/Project");
const mongoose = require("mongoose");
// The mongoose connect that will not show
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content, Accept, Content-Type, Authorization");
res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, PATCH, OPTIONS");
next();
});
app.use(bodyParser.json());
app.post("/api/stuff", (req, res, next) => {
const projet = new ProjectScheme({ ...req.body });
projet.save()
.then(() => res.status(201).json({ message: "Projet enregistré !" }))
.catch((error) => res.status(400).json({ error }));
});
const mongoose = require("mongoose");
const ProjectScheme = mongoose.Schema({
title: { type:String, required:true },
description: { type:String, required:true },
imageUrl: { type:String, required:true },
href: { type:String, required:true },
github_href: { type:String, required:true },
});
module.exports = mongoose.model('Projet', ProjectScheme);
最后是/models/Project.js
const http = require('http');
const app = require('./app');
app.set('port', process.env.PORT || 3000);
console.log(process.env.PORT || 3000);
const server = http.createServer(app);
server.listen(process.env.PORT || 3000);
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const ProjectScheme = require("./models/Project");
const mongoose = require("mongoose");
// The mongoose connect that will not show
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content, Accept, Content-Type, Authorization");
res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, PATCH, OPTIONS");
next();
});
app.use(bodyParser.json());
app.post("/api/stuff", (req, res, next) => {
const projet = new ProjectScheme({ ...req.body });
projet.save()
.then(() => res.status(201).json({ message: "Projet enregistré !" }))
.catch((error) => res.status(400).json({ error }));
});
const mongoose = require("mongoose");
const ProjectScheme = mongoose.Schema({
title: { type:String, required:true },
description: { type:String, required:true },
imageUrl: { type:String, required:true },
href: { type:String, required:true },
github_href: { type:String, required:true },
});
module.exports = mongoose.model('Projet', ProjectScheme);
谢谢你的帮助。这将非常有帮助。我认为这也会帮助很多其他人。问题在于:
request_projets_post.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request_projets_post.send(JSON.stringify(json));
在第一行中,将内容类型设置为application/x-www-form-urlencoded
。在第二种情况下,您的主体是一个JSON字符串
您发送给函数的数据是URL编码的:
title=title&description=description&imageUrl=imageUrl&href=href&github_href=github_href
但在服务器上,您将主体解析为json:
app.use(bodyParser.json());
你不能混合编码。您需要决定是使用JSON还是URL编码:
title=title&description=description&imageUrl=imageUrl&href=href&github_href=github_href
JSON
在前端:
request_projets_post.setRequestHeader("Content-type", "application/json");
request_projets_post.send(JSON.stringify(json));
您提供给函数的数据是一个对象:
func_that_post_the_card_created(CHEMIN_AU_SERVEUR, {
title: title,
description: description,
imageUrl: imageUrl,
href: href,
github_href: github_href
});
后端不需要任何更改
URL编码
不要使用JSON.stringify:
const func_that_post_the_card_created = (path, data) => {
const request_projets_post = new XMLHttpRequest();
request_projets_post.open("POST", path, true);
request_projets_post.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request_projets_post.send(data);
};
func_that_post_the_card_created(CHEMIN_AU_SERVEUR, "title=title&description=description&imageUrl=imageUrl&href=href&github_href=github_href")
在服务器中删除该行
app.use(bodyParser.json());
并加上:
app.use(bodyParser.urlencoded({ extended: true }));
请参阅:问题是?->您在浏览器控制台中有什么错误?啊,对不起:问题是为什么我总是从前端得到这样的响应:POST 400(错误请求)啊,是的,谢谢。对不起,我必须检查一下。现在我确定了。在你的过程中,你应该做的第一件事是
console.log(req.body)代码>。只要确保你的变量确实包含你认为它们包含的内容。非常感谢。真正地你帮了我很多。看到有东西在工作真是太高兴了!!!!你知道很多关于Mongoose的知识来解释我如何清除MongooseAPI吗?不,我不知道Mongoose