server.js file looks like below:
const express = require('express');
const http = require('http');
const path = require('path');
//const request = require('request');
const app = express();
var cors = require('cors')
app.use(cors())
app.all('*',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-credentials", "true"),
// res.header("access-control-allow-methods", "GET, POST, PUT, DELETE, PATCH, OPTIONS"),
res.header("access-control-allow-methods", "GET, POST, PUT, DELETE, PATCH, OPTIONS"),
next();
});
var corsOptions = {
origin: 'http://localhost:8080',
optionsSuccessStatus: 200
}
const port = process.env.PORT || 3001;
app.use(express.static(__dirname + '/dist/myApp'));
app.get("/*", (req, res) => res.sendFile(path.join(__dirname)));
app.post("/dashboard", cors(corsOptions), function(req, res) {
console.log(req.headers); // the posted data
console.log(req.query.module);
res.sendStatus(200)
});
const server = http.createServer(app);
server.listen(port, () => console.log('Running......'));
when i do node server.js and hit http://localhost:3001/ hit in browser i am getting my page what i mentioned a /dashboard in this same file.
但是我正在获取状态代码:404未找到。网络选项卡中显示的URL为http://localhost:3001/student/allstudent。还有什么我应该改变。如果以具有4200端口的proxy.conf.json开头,它将正常工作。但是现在我没有以proxy.conf.json身份启动,因为我正在启动node server.js。可以帮助我。我们是否应该提供Express的任何代理服务器而不是角度节点服务器。
💡这是我的文件夹结构示例:
/**
* dist
* - myApp
* - index.html
* src
* index.js
* package.json
*/
在我的index.js
中,我使用的是您上面的代码,但是在您的app.get('/*')
中,我的代码是在下面的change:
app.get("/*", (req, res) => res.sendFile(path.join(__dirname, '../dist/myApp', 'index.html')));
使用👆上方的代码,它可以正常工作。
我希望能对您有所帮助。