, когда я запускаю приложение реагирования одновременно с express на localhost и перехожу на localhost: 8000, я получаю созданную ошибку, проанализированную здесь в json. в консоли я получаю внутреннюю ошибку сервера 500.
const corsOptions = {
origin: function (origin, callback) {
console.log(origin)
if (whitelist.indexOf(origin) !== -1) {
callback(null, true)
} else {
callback(new Error('Not allowed by CORS'))
}
},
credentials: true,
enablePreflight: true
}
вот мой индекс для express
// TODO: make diff config for express in webpack to use imports instead of require
// with static it should console log to browser but isnt
// this isnt connected its just showing a mirror image of whats displaying on the dev server
// prolly cause its all getting bundled with same config
const express = require("express");
const logger = require('morgan');
const cors = require('cors');
const bodyParser = require('body-parser');
var createError = require("http-errors");
const app = express();
//use cors to allow cross origin resource sharing
app.use(
cors({
origin: 'http://localhost:3000',
credentials: true,
optionsSuccessStatus: 200
})
);
// settings cors options to allow origin
const whitelist = [
"http://localhost:8000/api/start",
"http://localhost:8000/api/create",
"http://localhost:3000"
]
const corsOptions = {
origin: function (origin, callback) {
console.log(origin)
if (whitelist.indexOf(origin) !== -1) {
callback(null, true)
} else {
callback(new Error('Not allowed by CORS'))
}
},
credentials: true,
enablePreflight: true
}
app.use(cors(corsOptions));
app.options("*", cors(corsOptions));
// err logging
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// hacky way to control how errs display
app.use(function (req, res, next) {
next(createError(404));
});
// 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 err stack in terminal
console.log(err.stack)
// render the error page
res.status(err.status || 500).json({ error: err.message, status: err.status })
});
let form = ["empty form"];
// should be same as react get
app.get('/api/start', function (req, res) {
console.log('Inside Home Login');
res.writeHead(200, {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
});
console.log('Forms : ', JSON.stringify(form));
res.JSON({ express: form });
});
//parsing the body of the req for form info
app.post('/api/create', function (req, res) {
const newForm = {
premiseId: req.body.premiseId,
password: req.body.password,
correct: req.body.correct,
};
forms.push(newForm);
console.log(req.body, form);
});
// serves static files from this folder
app.use(express.static("dist"));
// app starts listening to this port
app.listen(8000, () => console.log("Listening on port 8000!"));
context. js, который загружен в форму входа ниже
// used to get data from server
async componentDidMount() {
// test
await this.callApi()
.then(res => this.setState({ response: res.express }))
.catch(err => console.log(err));
}
// test function for api call
callApi = async () => {
const response = await fetch('http://localhost:8000/api/start');
const body = await response.json();
if (response.status !== 200) throw Error(body.message);
return body;
}
handleSubmit = async e => {
e.preventDefault();
const { loginPremise: {
premiseId,
password,
correct
} } = this.state;
const loginPremiseForm = {
premiseId,
password,
correct,
};
const response = await fetch('http://localhost:8000/api/create', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(loginPremiseForm),
});
const body = await response.text();
if (typeof body !== undefined) {
this.setState(prevState => ({
loginPremise: {
...prevState.loginPremise,
responseToPost: body
}
}));
}
};
handlePremiseFormChange = (e) => {
e.persist();
this.setState(prevState => ({
loginPremise: {
...prevState.loginPremise,
[e.target.name]: e.target.value
}
})
)
};
handleLoginFormChange = (e) => {
};
handleUserProfileFormChange = (e) => {
};
formatData = items => {
let tempItems = items.map(item => {
});
return tempItems;
};
getName = slug => {
let tempNames = [...this.state.sortedNames];
const name = tempNames.find(name => name.slug === slug);
return name;
};
handleFilterChange = event => {
const target = event.target;
const name = target.name;
// only use if adding checkboxes
let value = target.type === "checkbox" ? target.checked : target.value;
this.setState(
{
[name]: value
},
this.filterNames
);
};
filterNames = () => {
let {
firstName,
lastName,
Alias: {
differentFirst,
differentLast
},
address: {
houseNumber,
street,
apt,
suite,
city,
state,
zipCode,
}
} = this.state;
// all the names
let tempNames;
// numbers array
let numbersArray = [{ houseNumber }, { apt }, { suite }, { zipCode }]
// transform value from string to number
const parsedNumbers = (numbersArray) => {
const { houseNumber, apt, suite, zipCode } = [...numbersArray];
const tempArray = [];
const parser = (tempArray) => {
let tempNumbers = [...tempArray]
tempNumbers = tempNumbers.map(numbers => {
return parseInt(numbers);
});
return tempNumbers;
};
const parsedNumbersArray = parser(tempArray);
const defaultArray = parsedNumbersArray.map(parsednumber => {
return tempArray.filter(tempNumber => {
if (tempNumber === parsedNumber) {
tempNumbe = parsedNumber;
}
})
})
return defaultArray;
};
this.setState({ sortedNames: tempNames });
};
render() {
return (
<UserContext.Provider
value={{
...this.state,
premiseFormChange: this.handlePremiseFormChange,
onSubmit: this.handleSubmit
}}
>
{this.props.children}
</UserContext.Provider>
);
}
}
const UserConsumer = UserContext.Consumer;
// high order component to wrap components that need to recieve current state or methods
export function withUserConsumer(Component) {
return function consumerWrapper(props) {
return (
<UserConsumer>
{value => <Component {...props} context={value} />}
</UserConsumer>
);
};
}
export { UserProvider, UserConsumer, UserContext };
форма входа в систему с использованием контекста для выполнения тестового вызова API
import React from "react";
import { useContext } from "react";
import { UserContext } from "../../../../Context";
import {
Button,
Form,
Grid,
Header,
Message,
Segment
} from "semantic-ui-react";
const Login = ({ props }) => {
const context = useContext(UserContext);
const {
loginPremise: {
correct
}, premiseFormChange, onSubmit } = context;
console.log(context, correct)
return (
<React.Fragment>
<Grid id="login_grid" centered >
<Grid.Column>
<Header as="h1" textAlign="center">
Welcome
</Header>
<Segment>
<Form size="large" onSubmit={onSubmit}>
{/* Email Address for form */}
<Form.Input
fluid
icon="user"
iconPosition="left"
name="premiseId"
placeholder="Premise Id"
autoComplete="username"
onChange={premiseFormChange}
error={(!correct || undefined) && { content: 'Please enter correct premise id', pointing: 'below' }}
/>
{/* password for form */}
<Form.Input
fluid
icon="lock"
iconPosition="left"
placeholder="Password"
name="password"
type="password"
autoComplete="current-password"
onChange={premiseFormChange}
error={(!correct || undefined) && { content: 'Please enter correct password', pointing: 'below' }}
/>
{/* submit for form */}
<Button
color="blue"
fluid size="large"
>
Login
</Button>
</Form>
</Segment>
{/* Registeration Link*/}
<Message>
Not registered yet? <a href="#">Sign Up</a>
</Message>
</Grid.Column>
</Grid>
</React.Fragment>
);
};
export default Login;
что может вызывать ошибку при монтировании компонента формы?